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

145

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"]. I tried

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

but none of above doesn't work.

This question is tagged with javascript node.js

~ Asked on 2014-02-19 23:54:36

The Best Answer is


266

Try splitting on a regex like /\r?\n/ to be usable by both Windows and UNIX systems.

> "a\nb\r\nc".split(/\r?\n/)
[ 'a', 'b', 'c' ]

~ Answered on 2014-02-20 00:03:16


51

If the file is native to your system (certainly no guarantees of that), then Node can help you out:

var os = require('os');

a.split(os.EOL);

This is usually more useful for constructing output strings from Node though, for platform portability.

~ Answered on 2014-02-20 02:09:00


Most Viewed Questions: