Blender
Blender

Reputation: 298582

Ignoring trailing and leading newlines when splitting by \n?

I'm trying to split some text into individual lines while preserving whitespace for a JS syntax highlighter:

var text = '\n\n\ntest\n\ntext\n\n';

When I use .split('\n'), I get a bunch of blank elements in my array:

> text.split('\n');
["", "", "", "test", "", "text", "", ""]

Currently, I .strip() the text before splitting it, but that looks messy:

> text.replace(/^\s+|\s+$/g, '').split('\n');
["test", "", "text"]

Is there any way to disregard trailing and leading newlines when using .split()? I tried writing a regex, but that didn't go so well.

Upvotes: 4

Views: 229

Answers (3)

VisioN
VisioN

Reputation: 145478

Though I can't get your logic entirely, maybe the following helps you to do the parsing using split:

var text = "\n\n\ntest\n\ntext\n\n",
    parsed = ("\n" + text + "\n").split(/^\n+|\n+$|\n/).slice(1, -1);

console.log(parsed);   // ["test", "", "text"]

Upvotes: 0

elclanrs
elclanrs

Reputation: 94141

var text = '\n\n\ntest\n\ntext\n\n lorem ipsum';
var arr = text.match(/[ \w]+/g);

console.log(arr); //=> ["test", "text", " lorem ipsum"]

Upvotes: 2

Firas Dib
Firas Dib

Reputation: 2621

You could use split(/\n+/) to consume as many newlines as possible and then split.

Upvotes: 0

Related Questions