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?
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---^
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 ");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With