Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  4] [ 4]  / answers: 1 / hits: 23940  / 12 Years ago, mon, october 8, 2012, 12:00:00

I am currently using str.indexOf(word) to find a word in a string.
But the problem is that it is also returning parts of other words.



Example: I went to the foobar and ordered foo.
I want the first index of the single word foo, not not the foo within foobar.



I can not search for foo because sometimes it might be followed by a full-stop or comma (any non-alphanumeric character).


More From » regex

 Answers
99

You'll have to use regex for this:



> 'I went to the foobar and ordered foo.'.indexOf('foo')
14
> 'I went to the foobar and ordered foo.'.search(/bfoob/)
33


/bfoob/ matches foo that is surrounded by word boundaries.



To match an arbitrary word, construct a RegExp object:



> var word = 'foo';
> var regex = new RegExp('\b' + word + '\b');
> 'I went to the foobar and ordered foo.'.search(regex);
33

[#82709] Friday, October 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ross

Total Points: 477
Total Questions: 97
Total Answers: 98

Location: France
Member since Thu, May 6, 2021
3 Years ago
;