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

匆匆过客 提交于 2019-11-30 23:23:59

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/12773913/javascript-find-index-of-word-in-string-not-part-of-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!