JavaScript string with new line - but not using \n

前端 未结 8 2016
故里飘歌
故里飘歌 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:14

    The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n obviously). The reason \n exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings.

    When you have a string which looks like this:

    //Note lack of terminating double quote
    var foo = "Bob 
    

    Your code will have a syntax error at that point and cease to run.

    If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:

    //Perfectly valid code
    var foo = "Bob \
    is \
    cool.";
    

    However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.

    var foo = "Bob\nis\ncool.";
    
    0 讨论(0)
  • 2020-11-27 06:18

    you can use the following function:

      function nl2br (str, is_xhtml) {
         var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
         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<br>another line<br>another line

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

    this imitates the nl2br function in php...

    0 讨论(0)
提交回复
热议问题