How can I find the last occurrence of a word with word boundaries? I created a regex expression of /\btotal\b/
for the word. How would I use search() to find the last occurrence of this expression? Thanks in advance for the help!
You can use negative lookahead to get the last match:
/(\btotal\b)(?!.*\b\1\b)/
RegEx Demo 1
RegEx Demo 2
(?!.*\1)
is negative lookahead to assert that captured group #1 i.e. total
word is NOT present ahead of the present match.
Without using the lookaheads but using the same regex (having applied the g
, i.e. global, flag), the option would be to match the string with regex and get the last match.
var matches = yourString.match(/\btotal\b/g);
var lastMatch = matches[matches.length-1];
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