16

我目前正在使用str.indexOf("word")在字符串中查找单词。但问题是它也返回了其他单词的一部分。

示例:“我去了 foobar 并点了 foo。” 我想要单个单词“foo”的第一个索引,而不是 foobar 中的 foo。

我无法搜索“foo”,因为有时它后面可能会跟一个句号或逗号(任何非字母数字字符)。

4

3 回答 3

30

您必须为此使用正则表达式:

> '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/foo被单词边界包围的匹配项。

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

> var word = 'foo';
> var regex = new RegExp('\\b' + word + '\\b');
> 'I went to the foobar and ordered foo.'.search(regex);
33
于 2012-10-08T00:09:07.087 回答
6

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

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

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

于 2012-10-08T00:23:55.090 回答
0

正如前面的答案所建议的,我已经尝试过使用“.search”和“.match”,但只有这个解决方案对我有用。

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

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

使用 'i' 进行不区分大小写的搜索。

ComFreek在这里写了一个详细的答案

于 2020-02-19T21:48:35.763 回答