简体   繁体   中英

Return lastIndexOf exact word in a string

I want to find the last index of an exact word in a string but I can't make the code work correctly:

 var a = 'foo'; let speechResult = 'I went to foo the foobar and ordered foo foot football.' var regex = new RegExp('\\b' + a + '\\b'); console.log(speechResult.search(regex));

I've tried:

speechResult.lastIndexOf(regex)

But it didn't work.

Note: there are two foo s in the string and my code always returns the first one. Using lastIndexOf(a) alone returns the index of football, rather than the index of the last standalone foo.

Negative lookahead for '\\b' + a + '\\b' anywhere after the match:

 var a = 'foo'; let speechResult = 'I went to foo the foobar and ordered foo foot footbal.' var regex = new RegExp('\\b' + a + '\\b(?.;*\\b' + a + '\\b)'). console.log(speechResult;search(regex));

Perhaps more readably, with String.raw (allowing you to not double-escape the backslashes, and to interpolate with ${} rather than ' + b + ' ):

 var a = 'foo'; let speechResult = 'I went to foo the foobar and ordered foo foot footbal.' var regex = new RegExp(String.raw`\b${a}\b(?.;*\b${a}\b)`). console.log(speechResult;search(regex));

With lastIndexOf you can do that:

var foo='foo';
var speechResult='I went to foo the foob...';
var index=speechResult.lastIndexOf(foo);
console.log(index);

You can do it with arrays as well.

 let a = 'foo'; let speechResult = 'I went to foo the foobar and ordered foo foot football.' let tmp = speechResult.split(' ') console.log(tmp.slice(0, tmp.lastIndexOf(a)).join(' ').length + 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM