Javascript 在字符串中找到单词索引 /不是这个词的一部分/

我目前使用
str.indexOf/"word"/

, 在一行中找到一个单词。
但问题是它还返回其他单词的部分。

例子: "I went to the foobar and ordered foo."
我想要一个单词的第一个索引 "foo", 对这个计划没有生气。

我无法搜索 "foo", 因为有时它可能遵循完整的停止或逗号 /任何不是字母数字符号/.
已邀请:

奔跑吧少年

赞同来自:

为此,您必须使用 regex:


> '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

卫东

赞同来自:

在一般情况下,使用 RegExp constrcutor 创建由单词界限的正则表达式:


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


请注意,连字符被认为是单词的界限,因此在阳光下干燥的两个词是两个词。

冰洋

赞同来自:

我试过了 ".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' 搜索而不注册。

发布了详细的答案

要回复问题请先登录注册