Convert HTML encoded & lt; br / & gt; in html new line tag in jquery.text ()

I have text in a variable sometext

that I want to assign div

using $('div').text(sometext);

. The problem is that everyone <br/>

is sometext

turning into &lt; br/ &gt;

. I cannot use $('div').html()

because there is a lot of internal structure that I want to store in div

, so I can only use the function .text()

.

So, once I have passed the text over div

, is there a way to change the encoded tag <br/>

to a real line break in HTML? I mean something like this:

$('div').convertMyBRsToHTML();

      

+3


source to share


2 answers


The requested function should look like this:

$.fn.convertMyBRsToHTML = function(text){
    this.text(text);
    this.html(this.html().replace(/&lt;br\s*\/&gt;/g,'<br/>'));
    return this;
}

      



Now you can use:

$(YOUR_SELECTOR).convertMyBRsToHTML("<b>Some</b> new text.<br />next line<br />and so on");

      

+5


source


You can replace <br>

before setting the text:



$('div').text(sometext.replace(/<br\s*\/?>/gi, '\n');

      

+2


source







All Articles