JavaScript Newline Character

后端 未结 4 1448
灰色年华
灰色年华 2020-12-29 04:10

From this question, this ...

lines = foo.value.split(/\\r\\n|\\r|\\n/);

is one way to split a string, but how do I join it back with newlin

相关标签:
4条回答
  • 2020-12-29 04:22

    If you want to join using newline characters, just do:

    lines.join("\r\n");
    

    But if you want to display on the HTML page, you'd want to wrap each line in <p></p> tags:

    html = "<p>" + lines.join("</p><p>") + "</p>";
    
    0 讨论(0)
  • 2020-12-29 04:22

    As said, join is the best, but here is the hard way (untested, I hope it's not too trivial):

    var result;
    
    for (i=0;i<lines.length;i++){
       result+=lines[i]+"\r\n"; //depends on OS
    }
    
    0 讨论(0)
  • 2020-12-29 04:24

    Split it on /\r?\n/, in case the string includes the carriage returns with newlines.

    join it with '\n', in any browser and any os.

    0 讨论(0)
  • 2020-12-29 04:31

    You can use the Array object's join method to glue together array elements into a string:

    lines.join("\r\n");
    

    In CSS: remember to use

    white-space: pre;
    
    0 讨论(0)
提交回复
热议问题