如何检查字符串是否包含javascript中的WORD?

Kha*_*111 2 javascript string split

因此,您可以使用 .includes() 方法轻松检查字符串是否包含特定子字符串。

我有兴趣查找字符串是否包含单词。

例如,如果我搜索“on”字符串,“phones are good”,它应该返回 false。并且,它应该为“将其保留在桌子上”返回 true。

Mah*_*Ali 12

您首先需要使用将其转换为数组split(),然后使用includes()

string.split(" ").includes("on")
Run Code Online (Sandbox Code Playgroud)

只需要传递的空白" ",以split()获取所有单词

  • 如果单词之间用逗号分隔怎么办? (3认同)
  • `.includes()` 适用于字符串和数组,因此不需要 `.split()`。 (2认同)

Gré*_*EUT 6

这称为regex - 正则表达式

当您需要解决这些问题时,您可以使用101regex网站(它有帮助)。也带有自定义分隔符的单词。


function checkWord(word, str) {
  const allowedSeparator = '\\\s,;"\'|';

  const regex = new RegExp(
    `(^.*[${allowedSeparator}]${word}$)|(^${word}[${allowedSeparator}].*)|(^${word}$)|(^.*[${allowedSeparator}]${word}[${allowedSeparator}].*$)`,

    // Case insensitive
    'i',
  );
  
  return regex.test(str);
}

[
  'phones are good',
  'keep it on the table',
  'on',
  'keep iton the table',
  'keep it on',
  'on the table',
  'the,table,is,on,the,desk',
  'the,table,is,on|the,desk',
  'the,table,is|the,desk',
].forEach((x) => {
  console.log(`Check: ${x} : ${checkWord('on', x)}`);
});
Run Code Online (Sandbox Code Playgroud)


解释

我在这里为每种可能创建多个捕获组:

(^.*\son$)on 是最后一个词

(^on\s.*)on 是第一个词

(^on$)on 是唯一的词

(^.*\son\s.*$)on 是一个中间词

\s表示空格或换行

const regex = /(^.*\son$)|(^on\s.*)|(^on$)|(^.*\son\s.*$)/i;

console.log(regex.test('phones are good'));
console.log(regex.test('keep it on the table'));
console.log(regex.test('on'));
console.log(regex.test('keep iton the table'));
console.log(regex.test('keep it on'));
console.log(regex.test('on the table'));
Run Code Online (Sandbox Code Playgroud)



gkg*_*kgk 1

您可以使用.includes()并检查该词。为了确保它是一个单词而不是另一个单词的一部分,请验证您找到它的位置后面是否有空格、逗号、句号等,并且前面也有其中一个。