我有一个代表文本段落的字符串。

var paragraph = "It is important that the word cold is not partially selected where we search for the word old";

我希望能够搜索本段“单词”的索引,并在“ word”上具有确切的匹配。例如,在搜索“旧”时。我只能得到1个结果,而不是2个结果,因为与“冷”中的“旧”匹配是无效的。

有帮助吗?

解决方案

您需要使用单词边界搜索 \b:

var idx = paragraph.search(/\bold\b/i);

这与单词分开的空间,破折号等匹配。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top