0

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!

P.S.

Assume that all newlines are normalized to \n.

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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

\s* matches zero or more whitespaces

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

1 Comment

This code doesn't work. 'bar \n fooo \n \n \n'.match(/(\s*\n\s*)+$/g).length returns 1, but OP expects 3.

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.