Javascript在字符串中找到单词的索引(不是单词的一部分)

10 javascript regex search indexof text-search

我目前正在使用str.indexOf("word")字符串中查找单词.但问题在于它还会返回其他词语的部分内容.

例如:"我去了foobar并订购了foo." 我想要单词"foo"的第一个索引,而不是foobar中的foo.

我无法搜索"foo",因为有时它可能会跟随一个句号或逗号(任何非字母数字字符).

Ble*_*der 20

你必须使用正则表达式:

> 'I went to the foobar and ordered foo.'.indexOf('foo')
14
> 'I went to the foobar and ordered foo.'.search(/\bfoo\b/)
33
Run Code Online (Sandbox Code Playgroud)

/\bfoo\b/foo由字边界包围的匹配.

要匹配任意单词,请构造一个RegExp对象:

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


Rob*_*obG 5

对于一般情况,使用 RegExp 构造器创建以字边界为界的正则表达式:

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

请注意,连字符被视为单词边界,因此晒干是两个单词。