JavaScript string with new line - but not using \n

前端 未结 8 2087
故里飘歌
故里飘歌 2020-11-27 05:44

I have a string that has new lines in. I am wanting to convert these to HTML
s, but I\'m having a hard time detecting them.

Imagine a JavaScri

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 06:18

    you can use the following function:

      function nl2br (str, is_xhtml) {
         var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
    ' : '
    '; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); }

    like so:

    var mystr="line\nanother line\nanother line";
    mystr=nl2br(mystr);
    alert(mystr);
    

    this should alert line
    another line
    another line

    the source of the function is from here: http://phpjs.org/functions/nl2br:480

    this imitates the nl2br function in php...

提交回复
热议问题