How in node to split string by newline ('\n')?

后端 未结 7 1824
南笙
南笙 2020-11-29 17:30

How in node to split string by newline (\'\\n\') ? I have simple string like var a = \"test.js\\nagain.js\" and I need to get [\"test.js\", \"again.js\"]<

7条回答
  •  有刺的猬
    2020-11-29 18:19

    It looks like regex /\r\n|\r|\n/ handles CR, LF, and CRLF line endings, their mixed sequences, and keeps all the empty lines inbetween. Try that!

    function splitLines(t) { return t.split(/\r\n|\r|\n/); }
    
    // single newlines
    splitLines("AAA\rBBB\nCCC\r\nDDD");
    // double newlines
    splitLines("EEE\r\rFFF\n\nGGG\r\n\r\nHHH");
    // mixed sequences
    splitLines("III\n\r\nJJJ\r\r\nKKK\r\n\nLLL\r\n\rMMM");
    

    You should get these arrays as a result:

    [ "AAA", "BBB", "CCC", "DDD" ]
    [ "EEE", "", "FFF", "", "GGG", "", "HHH" ]
    [ "III", "", "JJJ", "", "KKK", "", "LLL", "", "MMM" ]
    

    You can also teach that regex to recognize other legit Unicode line terminators by adding |\xHH or |\uHHHH parts, where H's are hexadecimal digits of the additional terminator character codepoint (as seen in Wikipedia article as U+HHHH).

提交回复
热议问题