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

后端 未结 7 1879
南笙
南笙 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:24

    A solution that works with all possible line endings including mixed ones and keeping empty lines as well can be achieved using two replaces and one split as follows

    text.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/);
    

    some code to test it

      var CR = "\x0D";  //   \r
      var LF = "\x0A";  //   \n
    
      var mixedfile = "00" + CR + LF +            // 1 x win
                      "01" + LF +                 // 1 x linux
                      "02" + CR +                 // 1 x old mac
                      "03" + CR + CR +            // 2 x old mac
                      "05" + LF + LF +            // 2 x linux
                      "07" + CR + LF + CR + LF +  // 2 x win
                      "09";
    
      function showarr (desc, arr)
      {
         console.log ("// ----- " + desc);
         for (var ii in arr)
            console.log (ii + ") [" + arr[ii] +  "] (len = " + arr[ii].length + ")");
      }
    
      showarr ("using 2 replace + 1 split", 
               mixedfile.replace(/\r\n/g, "\r").replace(/\n/g, "\r").split(/\r/));
    

    and the output

      // ----- using 2 replace + 1 split
      0) [00] (len = 2)
      1) [01] (len = 2)
      2) [02] (len = 2)
      3) [03] (len = 2)
      4) [] (len = 0)
      5) [05] (len = 2)
      6) [] (len = 0)
      7) [07] (len = 2)
      8) [] (len = 0)
      9) [09] (len = 2)
    

提交回复
热议问题