How in node to break a line into a new line ('\ n')?

How in node to break a line into a new line ('\ n')? I have a simple string, for example var a = "test.js\nagain.js" , and I need to get ["test.js", "again.js"] . I tried

 a.split("\n"); a.split("\\n"); a.split("\r\n"); a.split("\r"); 

but nothing above works.

+48
javascript
Feb 19 '14 at 23:54
source share
6 answers

Try splitting it into a regular expression, such as /\r?\n/ , for use on both Windows and UNIX systems.

 > "a\nb\r\nc".split(/\r?\n/) [ 'a', 'b', 'c' ] 
+105
Feb 20 '14 at 0:03
source share

If the file is native to your system (of course, no guarantees for this), then Node can help you:

 var os = require('os'); a.split(os.EOL); 

This is usually more useful for building output strings from Node, although for platform portability.

+22
Feb 20 '14 at 2:09
source share
 a = a.split("\n"); 



Note that split ting returns a new array, not just assigning it to the original string. You need to explicitly save it in a variable.

+16
Feb 19 '14 at 23:59
source share

I created an eol module for working with line endings in node or browsers. It has a separation method like

 var lines = eol.split(text) 
+3
Feb 18 '17 at 8:37
source share

The first should work:

 > "a\nb".split("\n"); [ 'a', 'b' ] > var a = "test.js\nagain.js" undefined > a.split("\n"); [ 'test.js', 'again.js' ] 
+2
Feb 19 '14 at 23:56
source share

You need simple quotes

 string.split('\n'); 

Simple quotes work here.

+1
Sep 08 '17 at 18:21
source share



All Articles