Javascript find index of word in string (not part of word)

For a general case, use the RegExp constrcutor to create the regular expression bounded by word boundaries:

function matchWord(s, word) {
  var re = new RegExp( '\\b' + word + '\\b');
  return s.match(re);
}

Note that hyphens are considered word boundaries, so sun-dried is two words.


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(/\bfoo\b/)
33

/\bfoo\b/ 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