6

While working on a project I ran across a bug and found this unexpected behaviour:

If I call .replace() on a string and set the result to a div using .text() the replace function works as I expect.

However, if I call .replace() on a string and set the result to a div using .html(), the targeted text is not replaced in the string.

Here's an example of what I mean:

 $('#result1').text('¤cyId'.replace('¤cyId','&currencyId')); // works
 $('#result2').html('¤cyId'.replace('¤cyId','&currencyId')); // doesnt work 

    var result = '¤cyId'.replace('¤cyId','&currencyId')
 $('#result3').text(result); // works
 $('#result4').html(result); // doesnt work 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result1"></div><br>
<div id="result2"></div><br>
<div id="result3"></div><br>
<div id="result4"></div>

I see that using .text() instead of .html() resolves the issue, but...

Why does this happen?

Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • *"the targeted text is not replaced in the string"* - No, the targeted text *is* replaced. It's what happens when the result is treated as html that is causing your issue. – nnnnnn Aug 29 '15 at 23:53

3 Answers3

6

The replaces works just fine.

It only looks like the wrong string ends up in the elements when you use the html method because &curren is decoded into ¤ by the browser, so &currencyId is shown as ¤cyId.

When you use the text method the text is not decoded as HTML code, so .text("&currencyId") has the same effect as.html("&amp;currencyId").

The HTML entity for the ¤ character is &curren;, but the browser also accepts the form &curren without the semicolon.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

Because &curren is a html entity, and .html resolves html entities whilst .text leaves them verbatim.

sahbeewah
  • 2,690
  • 1
  • 12
  • 18
1

try

$('#result2').html('¤cyId'.replace('¤cyId','&amp;currencyId'));

& in html should be &amp;

galchen
  • 5,252
  • 3
  • 29
  • 43