Given a string like the following in JavaScript
var a = 'hello world\n\nbye world\n\nfoo\nbar\n\nfoo\nbaz\n\n';
I want to split it into an array like this
['hello world', '\n\n', 'bye world', '\n\n', 'foo\nbar', '\n\n', 'foo\nbaz', '\n\n'].
If the input is var a = 'hello world\n\nbye world', the result should be ['hello world', '\n\n', 'bye world'].
In other words, I want to split the string around ‘\n\n’ into an array such that the array contains the ‘\n\n’ as well. Is there any neat way to do this in JavaScript?
Here’s a one liner:
Here’s how it works:
\n\nmatches the two consecutive newline characters(?:[^\n]|\n(?!\n))+matches any sequence of one or more character of either[^\n]not a newline character, or\n(?!\n)a newline character but only if not followed by another newline characterThis recursive pattern can be applied on any length:
Update Here’s a modification for
String.prototype.splitthat should add the feature of containing a matched separator as well: