How do I find line breaks and replace with <br> elements in JavaScript?

蓝咒 提交于 2019-12-05 11:10:50

I'd cover my bets by handling \r\n (the sequence), and then handling \r and \n through a character class, like this:

text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');

The first replace turns the sequence \r\n into <br />. The second replace replaces any \r or \n characters found on their own with the string.

More on regular expressions in JavaScript here.

ECMAScript normalizes line breaks in strings to "\n\r" and the DOM normalizes line breaks in strings to "\n". Both of those OS agnostic which these formats:

  • Windows - CRLF
  • Unix - LF
  • Old Mac - CR

The right way to accomplish this task depends on how you are receiving the string and how you are writing it out.

To handle windows new line characters try

text = text.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />');

Another solution for both types of line endings

str.replace(new RegExp('\r?\n','g'), '<br />');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!