简体   繁体   中英

JavaScript Regex: Number of trailing newlines in a string

I'm trying to find the number of trailing newlines in a string. Consider the following example:

var foo = 'bar \n fooo \n   \n   \n';

For foo i should get back 3, meaning it won't count the newline between bar and fooo.

The way that I'm doing it right now is matching all trailing whitespaces /\\s*$. and then matching /\\n/g against the result to get the exact number. While this works, I was wondering if there is a way to do it with only one regular expression. Thanks for you help!

PS

Assume that all newlines are normalized to \\n .

(\\s*\\n\\s*)+$

\\s* matches zero or more whitespaces

'your string here'.match(/(\\s*\\n\\s*)+$/g).length;

You could use /\\s+$/ to find all trailing whitespace, then count the number of \\n found in that string.

For example:

var foo = 'bar \n fooo \n   \n   \n';
var trailingLines = foo .match(/\s+$/)[0].split('\n').length - 1; 

Alternatively, you could use a lookahead in a pattern like this:

/\n(?=\s*$)/g

This will match any \\n which is followed by zero or more whitespace characters and the end of the string.

For example:

var foo = 'bar \n fooo \n   \n   \n';
var trailingLines = foo.match(/\n(?=\s*$)/g).length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM