0

Question:
Using regular expressions in javascript, if I have a string that contains zero or more newlines or carriage returns, what is the best way to tell how many characters are after the last newline or carriage return?

Attempts:
I've tried various regular expressions, but with no luck. Say I have the string:

"_\nHELLO\nWORLD\nSALUTATIONS"
In normal output, it looks like this:
_ HELLO WORLD SALUTATIONS

Shouldn't /^(\r|\n){1}/g find a string globally g, with only one occurance {1} of a return or newline (\r|\n), or, in this case, "SALUTATIONS"? Instead no match is found.

4 Answers 4

4

How about not using a regex

string.split(/\r|\n/).pop().length;

That splits the string on newlines, pops off the last one and get's the number of characters with length

Sign up to request clarification or add additional context in comments.

5 Comments

does "pop" pull the last element in the array created by the split?
You should split on /\r|\n/, though
@Bergi - does any browser really use \r now? I know old IE used to return \r\n, and not just \r, but I didn't think this was an issue anymore ?
It might not be necessary, yes, but we don't know where the string came from and it's what the OP asked for.
@Bergi - sure, changed it, doesn't really matter to me?
1

No, your regex will find CRs/NLs only at the very beginning of the string, because you have an ^ anchor right there.

To find the last one, you rather will want to anchor your expression at the end of the string:

/[\r\n]([^\r\n]*)$/

By matching that, you will get all the characters after the last linebreak in the first capturing group.

Comments

0

Try this:

string.length - string.lastIndexOf('\n') - 1

Or if you really need to also check \r,

string.length - string.search(/[\n\r].*?$/) - 1

1 Comment

Should be Math.max(string.lastIndexOf('\n'), string.lastIndexOf('\r'))
0

A short and simple way would be this

console.log(text.match(/.*$/)[0].length);

$ marks the end of the string and by default . does not match line breaks, so the matched result is exactly the last line.

Comments

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.