benhowdle89
benhowdle89

Reputation: 37464

Split string into array of characters, keep certain sequence together (JavaScript)

I have my string:

var str = '123\r\nabc';

Which I'd like to produce this array:

["1", "2", "3", "

", "a", "b", "c"]

So, I'm looking to split it by character, but to keep \r\n together as one element in the resulting array.

My failed attempts:

console.log(str.split(/\r\n|/)); // removes \r\n
console.log(str.split(/\r\n/)); // splits by \r\n

Upvotes: 2

Views: 102

Answers (2)

anubhava
anubhava

Reputation: 785008

You can use this regex in split:

var str = "123\r\nabc";
console.log( str.split(/(\r\n)?/).filter(Boolean) );
  • Capture group around \r\n will make sure to capture it in the resulting array.
  • filter(Boolean) is used to filter out undefined elements from array.

Output:

["1", "2", "3", "
↵", "a", "b", "c"]

Upvotes: 1

Ry-
Ry-

Reputation: 224886

You can’t do this with split alone – /(\r\n)?/, for example, would leave undefineds in the result – so you’ll need to resort to match instead.

var result = str.match(/\r\n|[\S\s]/g);

where [\S\s] is . but including newlines. Note that result will be null on an empty string.

Upvotes: 3

Related Questions