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','¤cyId')); // works
$('#result2').html('¤cyId'.replace('¤cyId','¤cyId')); // doesnt work
var result = '¤cyId'.replace('¤cyId','¤cyId')
$('#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?
Remove All Line Breaks from a String We can remove all line breaks by using a regex to match all the line breaks by writing: str = str. replace(/(\r\n|\n|\r)/gm, ""); \r\n is the CRLF line break used by Windows.
Remove line breaks QUICKLY with Notepad++. Just use ctrl+a and then ctrl+j and all your line breaks are removed!
The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks. The pattern /g checks across all the string occurrences.
The replaces works just fine.
It only looks like the wrong string ends up in the elements when you use the html
method because ¤
is decoded into ¤
by the browser, so ¤cyId
is shown as ¤cyId
.
When you use the text
method the text is not decoded as HTML code, so .text("¤cyId")
has the same effect as.html("&currencyId")
.
The HTML entity for the ¤
character is ¤
, but the browser also accepts the form ¤
without the semicolon.
Because ¤ is a html entity, and .html resolves html entities whilst .text leaves them verbatim.
try
$('#result2').html('¤cyId'.replace('¤cyId','&currencyId'));
& in html should be &
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With