Aaron Thomas
Aaron Thomas

Reputation: 5281

Javascript regex match the last occurance

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.

Upvotes: 0

Views: 76

Answers (4)

bukart
bukart

Reputation: 4906

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.

Upvotes: 0

adeneo
adeneo

Reputation: 318342

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

Upvotes: 4

Oriol
Oriol

Reputation: 288620

Try this:

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

Or if you really need to also check \r,

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

Upvotes: 0

Bergi
Bergi

Reputation: 665361

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.

Upvotes: 1

Related Questions