Conor O'Brien
Conor O'Brien

Reputation: 1027

How might I split a string by every nth character in JavaScript?

I need to split a string into an array; my string will look something like this:

"6 3\n-3 30 23 -1 0 4 5\n5 4\n13 -3 -20 -4 -1"

Expanded, that looks like this:

"6 3
-3 30 23 -1 0 4 5
5 4
13 -3 -20 -4 -1"

I want to split this string into an array like this:

["6 3\n-3 30 23 -1 0 4 5","5 4\n13 -3 -20 -4 -1"]

That is, split the original string at every second \n character. I would also like a way to split some string at every nth appearance of some character. Any help is appreciated!

Upvotes: 1

Views: 999

Answers (1)

anubhava
anubhava

Reputation: 785058

You can use match instead:

var s = "6 3\n-3 30 23 -1 0 4 5\n5 4\n13 -3 -20 -4 -1";
var m = s.match(/[^\n]+\n[^\n]+/g);
//=> ["6 3\n-3 30 23 -1 0 4 5", "5 4\n13 -3 -20 -4 -1"]

Upvotes: 2

Related Questions