17

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

  • 3
    You have six questions which don't have accepted answers. Go back and accept an answer and people will be willing to post to this one. – jeremy Oct 08 '12 at 00:05
  • Ok thanks I did not know I had a persistant account as "user759885", I have gone through and done so. –  Oct 08 '12 at 00:09

3 Answers3

31

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
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Had a go at making a general case but my implementation doesn't seem to be working. `reg = '/\b' + word+ '\b/'; str.indexOf(reg);` –  Oct 08 '12 at 00:15
  • If you want to compose the regex you need two steps: double scape the "\" ("\\b") and call the RegExp constructor: `reg = new RegExp("\\b" + word + "\\b");` – A. Matías Quezada Oct 08 '12 at 00:21
  • Ah, I see indexOf does not take regex so you have used `search()`. My final solution was to use `reg = '\\b(' + word + ')\\b';` `str.indexOf(reg);` –  Oct 08 '12 at 00:21
  • @user759885: See my edit. You'll have to construct a `RegExp` object. – Blender Oct 08 '12 at 00:22
  • Its not proper solution. for example, var word = '.'; var regex = new RegExp('\\b' + word + '\\b'); alert('I went to the foobar and ordered foo.'.search(regex)); it will give `0`. – immayankmodi Dec 02 '12 at 12:57
  • @MMTac: JavaScript doesn't have an equivalent of Python's `re.escape()`, so the dot isn't being treated as a literal dot. – Blender Dec 02 '12 at 21:02
  • @Blender: Thanks for such a guidence. – immayankmodi Dec 03 '12 at 03:37
  • 1
    @Blender FYI `\\b` boundaries in javascript do not work for non-English but otherwise perfectly alphanumeric characters like à, é, ö. `new RegExp("\\bestá\\b").test('¿dónde está la alcaldesa?')` returns `False`, but curiously `new RegExp("\\bdónde\\b").test('¿dónde está la alcaldesa?')` returns True. – user3871 Jun 02 '18 at 05:19
  • @Growler did you know how to solve this issue you are talking about? I have the same issue on a translation script that's not working with the string "se acordó" because it has a "ó" at the end. – videomugre Mar 05 '21 at 17:45
7

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

I have tried both with ".search" and ".match", as suggested in the previous answers, but only this solution worked for me.

var str = 'Lorem Ipsum Docet';
var kw  = 'IPSUM';
var res = new RegExp('\\b('+kw+')\\b','i').test(str);

console.log(res); // true (...or false)

With the 'i' for case insensitive search.

ComFreek wrote a detailed answer here

P.O.W.
  • 1,895
  • 1
  • 16
  • 14