如何在 javascript 中的字符串中搜索单词(不仅仅是子字符串)?

How to search for a word (not just a substring) within a string in javascript?

我熟悉在字符串中搜索给定子字符串:

if (string.indexOf(substring) > -1) {
    var containsSubstring = true;
}

但是如果子串需要是一个词怎么办?

A word:

  • it must be at the beginning of the string with a space after it; or
  • at the end of the string with a space before it; or
  • in the middle of the string with a space on each side

如果我要查找子字符串 fox:

the quick brown fox // matches
fox jumps over the lazy dog // matches
quick brown fox jumps over // matches


the quick brownfox // does not match
foxjumps over the lazy dog // does not match
quick brownfox jumps over // does not match
quick brown foxjumps over // does not match
quick brownfoxjumps over // does not match

有什么方法可以使用 indexOf 实现上述结果,还是我需要使用正则表达式?

您可以通过检查它是否位于字符串的开头并且之后有一个 space ,或者是否位于字符串的结尾并且之前有一个 space 来实现这一点,或者是在字符串的中间,前后有一个 space。

您可以使用search方法。

var string = "foxs sas"

var search = string.search(/\bfox\b/) >= 0? true : false;

console.log(search)

您是否尝试过使用带有单词边界的正则表达式:

if (/(\bfox\b)/g.test(substring)) {
    var containsSubstring = true;
}

https://regex101.com/r/G3iOGi/1