Find Last Occurrence of Regex Word

2020-07-07 01:57发布

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!

2条回答
萌系小妹纸
2楼-- · 2020-07-07 02:17

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];
查看更多
虎瘦雄心在
3楼-- · 2020-07-07 02:23

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.

查看更多
登录 后发表回答