0

consider following function

function myFunction() {
  var html = "CR_557!#$&'()*+,-./:;<=>?@[]^_`{|}";
  var data = html.substring(0, 14);
  var newData = '<span style="background-color:#F2E9B7">' + data + '</span>';
  return html.replace(data, newData);
}

console.log(myFunction());

the expected content for var html in the end should be:

"<span style=\"background-color:#F2E9B7\">CR_557!#$&amp;</span>'()*+,-./:;&lt;=&gt;?@[]^_`{|}"

but for some reason i am getting this:

"<span style=\"background-color:#F2E9B7\">CR_557!#CR_557!#$&amp;amp;</span>'()*+,-./:;&lt;=&gt;?@[]^_`{|}"

the characters CR_557!# are getting repeated for some reason not sure why.

2
  • It also repeats &amp; with &amp;amp;... Commented Apr 30, 2020 at 12:30
  • 2
    $& has a special meaning when used with String.prototype.replace(): "$& Inserts the matched substring." (Source) Commented Apr 30, 2020 at 12:37

1 Answer 1

2

As Andreas mentions in a comment, $& has a special meaning in the replacement parameter of String.prototype.replace.

To solve the problem, use a function as the replacement parameter:

function myFunction() {
  var html = "CR_557!#$&amp;'()*+,-./:;&lt;=&gt;?@[]^_`{|}";
  var data = html.substring(0, 14);
  var newData = '<span style="background-color:#F2E9B7">' + data + '</span>';
  return html.replace(data, function () { return newData  });
}

console.log(myFunction());

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.