Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp: Can I get the last matched index or search backwards/RightToLeft?

Suppose I have a string

foo bar baz foo bar baz foo bar baz foo bar baz 

I want to find for the last occurance of bar, how can I effectively do this? do I need to loop through add matches? In .NET I can do a RightToLeft search in JS, I guess I can't?

like image 579
Jiew Meng Avatar asked Nov 30 '10 12:11

Jiew Meng


2 Answers

bar(?!.*bar)

will find the last bar in a string:

bar   # Match bar
(?!   # but only if it's not followed by...
 .*   # zero or more characters
 bar  # literal bar
)     # end of lookahead

If your string may contain newline characters, use

bar(?![\s\S]*bar)

instead. [\s\S] matches any character, including newlines.

For example:

match = subject.match(/bar(?![\s\S]*bar)/);
if (match != null) {
    // matched text: match[0]
    // match start: match.index
}

You might also want to surround your search words (if they are indeed words composed of alphanumeric characters) with \b anchors to avoid partial matches.

\bbar\b(?![\s\S]*\bbar\b)

matches the solitary bar instead of the bar within foobar:

Don't match bar, do match bar, but not foobar!
  no match---^     match---^    no match---^
like image 67
Tim Pietzcker Avatar answered Oct 17 '22 11:10

Tim Pietzcker


Use the built-in function lastIndexOf:

"foo bar baz foo bar baz foo bar baz foo bar baz".lastIndexOf("bar");

If you want to find the last "word" "bar":

(" "+"foo bar baz foo bar baz foo bar baz foo bar baz"+" ").lastIndexOf(" bar ");
like image 32
user1537366 Avatar answered Oct 17 '22 10:10

user1537366