简体   繁体   中英

Replace new lines to <br>, without start of string,

I'm trying to replace new lines in java script to <br> 's. But...

$(this).html($(this).text().replace(/(\n|\r)/gm, "<br>")); 

and the others function like this one replaced first line too. So I'm getting formatted text with enters at the start. Example

<br> (?)
<br> (?)
Text
<br>

How to solve this issue ?

$(".class").each(function(){
    $(this).html($(this).text().replace(/\\n/g, "<br/>"));
}); 

You may need to remove the leading '\\n' from the string, like this:

$(".class").each(function() {
    $(this).html( $(this).text().trim('\n').replace(/\n/g, "<br/>") );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM