2

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, thanks! Yep, went with this in the end: return (input.match(/\r\n|[\S\s]/g) || [])
1

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.