简体   繁体   中英

Extra New Lines Being Printed When replacing <br> with '\n' in Javascript

I need a little assistance. I am converting br tag to '\\n' using javascript. But it is placing extra '\\n' characters in place of the present number of br tags...

The following text

dummy text dummy text dummy text dummy text dummy text dummy text <br><br>dummy text dummy text dummy text dummy text dummy text dummy text

is being replaced by

dummy text dummy text dummy text dummy text dummy text dummy text 



dummy text dummy text dummy text dummy text dummy text dummy text

I have tried many regular expressions and stuff available here on stackoverflow but all of them printing extra newlines.

Here is the expression that i am using at the moment.

str.replace(/<br>/g,'\n')

It happens Specially the content of the text box is loaded through nl2br in php.

See the following images.

This is when the page is loaded 这是页面加载时

This is when the edit is pressed and str.replace thing is called. 这是在按下编辑并调用str.replace时。

Can anyone tell where I am making the mistake?

Thanks

PHP's nl2br doesn't replace newlines, it simply adds <br /> tags to the existing newlines.

When your JS tries to "reverse" the operation, it results in the original newline being duplicated.

Your replacement should replace with the empty string to remove the <br /> tags.

Consider also using the CSS white-space: pre-wrap instead of nl2br , as this will preserve all whitespace, including newlines and multiple spaces!

只需使用

replace(/<br\s*\/?>\n/mg,"\n")

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