Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Last Occurrence of Regex Word

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!

like image 491
Sujay Garlanka Avatar asked Jul 20 '16 20:07

Sujay Garlanka


2 Answers

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.

like image 116
anubhava Avatar answered Oct 23 '22 16:10

anubhava


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];
like image 13
nicael Avatar answered Oct 23 '22 15:10

nicael