I was trying to split a text with unknown line delimiters into single lines (ignoring blank lines). The first regex that I tried was /(\r|\n)+/m but that didn't work; that splits "a\r\nb" into [ "a", "\n", "b" ] instead of the expected [ "a", "b" ]. I already found out /[\r\n]+/m does what I want it to, but the two regexes seem equivalent to me (if the capture group itself isn't important). What am I missing?
console.log("a\r\nb".split(/(\r|\n)+/m));
console.log("a\r\nb".split(/[\r\n]+/m));
The two regex patterns do match the same thing. The actual difference is the presence of the capture group in the first version. If we add a capture group to the second version, the splitting behavior is identical:
console.log("a\r\nb".split(/(\r|\n)+/m));
console.log("a\r\nb".split(/([\r\n])+/m));
Note that the behavior of split() is such that the contents of the capture group are included in the split output. As an alternative, you could have made the first capture group non capturing, and then again the splitting behavior would be the same:
console.log("a\r\nb".split(/(?:\r|\n)+/m));
console.log("a\r\nb".split(/[\r\n]+/m));