Javascript regex match skipping back to back new line

Viewed 79

So I have this string:

function abc() {\n\n    return def;\n}

And I use this:

string.match(/[^\r\n]+/g)

And it matches into 3 lines:

Match 1: function abc() {

Match 2: return def;

Match 3: }

But it is missing a fourth match which should be the new line with no characters after the '{'.

I am using the website https://regex101.com/r/ALvFIN/1/ to test.

Set to flavor: ECMAScript

Regex: /[^\r\n]+/g

Test String:

function abc() {

    return def;
}

Any idea how to correctly match the double \n\n with no characters on line 2? I have tried the whitespace \s and \S but not right. Starting to think I need to look at an alternative solution.

2 Answers

You seem to want to match a string of one or more non-linebreak chars or an empty line.

This logic means you simply want to split a string with a single line break sequence.

To match ASCII line breaks, CRLF, LF or CR, you can use /\r\n?|\n/.

To match any Unicode line break sequence, you can use /\r\n|[\r\n\f\u000b\u0085\u2028\u2029]/.

console.log("function abc() {\n\n    return def;\n}".split(/\r\n?|\n/))

// Any Unicode line break sequence:
var rx = /\r\n|[\r\n\f\u000b\u0085\u2028\u2029]/;
console.log("function abc() {\n\n    return def;\n}".split(rx))

And if you still want to use .match() simply add a ^$ alternative to your regex with /m flag to make ^ and $ match start/end of a line:

console.log("function abc() {\n\n    return def;\n}".match(/[^\r\n]+|^$/gm))

If you want to split the string into its constituent lines, you can use this: /^.*$/gm. Note the m option to enable multiline matching.

Related