如何在javascript中检查字符串是否包含一个单词?

6
因此,您可以使用.includes()方法轻松检查字符串是否包含特定的子字符串。
我想要查找一个字符串是否包含一个单词。
例如,如果我在字符串“phones are good”中搜索“on”,它应该返回false。并且,在“keep it on the table”中搜索时,它应该返回true。

1
例如,可以在单词两侧仅允许空格,或者使用\bword\b - Asons
8个回答

18

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

string.split(" ").includes("on")

只需将空格" "传递给split()即可获取所有单词


3
如果这些单词之间用逗号隔开呢? - adiga
4
.includes()函数适用于字符串和数组,所以不需要使用.split()函数。 - Scott Marcus
1
@Scott Marcus 是的,它可以在字符串上工作,但他想匹配整个单词。包含在字符串中的内容无法匹配整个单词。 - Maheer Ali
@Scott Marcus 意味着多于一个空格? - Maheer Ali
@Scott Marcus,但是OP并没有要求他的字符串要用,-;分隔。 - Maheer Ali
显示剩余8条评论

5

这被称为正则表达式 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)}`);
});


说明:

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

(^.*\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'));



以句点结尾的字符串无法通过。例如,“保持开启。” - Paul Hutchinson
regex = new RegExp('\b${word}\b') 这种方式更简单。 - Дмитро Булах

4

您可以使用.split()将字符串按空格 (\s+) 分割成数组,然后使用 .includes() 检查字符串数组中是否包含您要查找的单词:

const hasWord = (str, word) => 
  str.split(/\s+/).includes(word);
  
console.log(hasWord("phones are good", "on"));
console.log(hasWord("keep it on the table", "on"));

如果您担心标点符号,您可以首先使用.replace()(如这个答案所示)将其删除,然后再使用split()

const hasWord = (str, word) => 
  str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(/\s+/).includes(word);
  
console.log(hasWord("phones are good son!", "on"));
console.log(hasWord("keep it on, the table", "on"));


1
对我来说,这看起来是一个很好的答案。不知道为什么有人在没有给出自己的意见的情况下就踩了它。我会点赞它。 - Marcia Ong
1
@MarciaOng 谢谢 :) 很高兴我不是唯一认为 -1 不合理的人 - Nick Parsons
1
@NickParsons 很棒的回答。人们在投票之前应该先阅读和理解。这正是我所寻找的。 - Al Rosado

3
你可以拆分然后尝试查找:

const str = 'keep it on the table';
const res =  str.split(/[\s,\?\,\.!]+/).some(f=> f === 'on');
console.log(res);

此外,some 方法非常高效,因为如果任何一个谓词为真,则返回true。

当它有!,。,;等符号时怎么办? - epascarello
@epascarello,感谢您的精彩评论!我已经编辑了我的答案。 - StepUp

1
您可以使用 .includes() 方法来查找单词。为了确保它是一个完整的单词而不是其它单词的一部分,需要验证找到它的位置之后是否跟随着空格、逗号、句号等符号,并且该位置之前也有这些符号中的一个。

1
or better use regex - Aarif
@Aarif 这也是一个不错的做法。 - gkgkgkgk

0
一个简单的版本只需要根据空白字符将其分割开来,并在生成的数组中查找相应的单词即可:
"phones are good".split(" ").find(word => word === "on") // undefined

"keep it on the table".split(" ").find(word => word === "on") // "on"

虽然这只是按空格拆分,但当您需要解析文本(取决于输入)时,您会遇到比空格更多的单词分隔符。在这种情况下,您可以使用正则表达式来处理这些特殊字符。例如:

"Phones are good, aren't they? They are. Yes!".split(/[\s,\?\,\.!]+/)

-2
我会按照以下假设进行操作:
  1. 句子开头的单词总是有一个尾随空格。
  2. 句子结尾的单词总是有一个前置空格。
  3. 句子中间的单词总是有一个前后空格。
因此,我会按照以下方式编写代码:

function containsWord(word, sentence) {
    return (
       sentence.startsWith(word.trim() + " ") ||
       sentence.endsWith(" " + word.trim()) ||
       sentence.includes(" " + word.trim() + " "));
}

console.log(containsWord("test", "This is a test of the containsWord function."));


-2

请尝试以下方法 -

var mainString = 'codehandbook'
var substr = /hand/
var found = substr.test(mainString)
if(found){
  console.log('Substring found !!')
} else {
  console.log('Substring not found !!')
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接