Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does using .html() break this Replace expression?

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?

like image 606
Wesley Smith Avatar asked Aug 29 '15 23:08

Wesley Smith


People also ask

How do you remove line breaks from a string?

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.

How do I remove a line break in Notepad ++?

Remove line breaks QUICKLY with Notepad++. Just use ctrl+a and then ctrl+j and all your line breaks are removed!

How do I replace all line breaks in a string with br /> elements?

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.


3 Answers

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.

like image 188
Guffa Avatar answered Oct 14 '22 20:10

Guffa


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

like image 45
sahbeewah Avatar answered Oct 14 '22 21:10

sahbeewah


try

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

& in html should be &amp;

like image 1
galchen Avatar answered Oct 14 '22 20:10

galchen