Sara Ree
Sara Ree

Reputation: 3543

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 foos 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.

Upvotes: 0

Views: 67

Answers (2)

hibernate fariala
hibernate fariala

Reputation: 74

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);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371168

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));

Upvotes: 2

Related Questions