【问题标题】:How to check if a string contains a WORD in javascript? [duplicate]如何检查字符串是否包含javascript中的WORD? [复制]
【发布时间】:2019-08-05 09:31:23
【问题描述】:

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

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

例如,如果我对字符串“电话很好”应用搜索“on”,它应该返回 false。而且,它应该为“把它放在桌子上”返回 true。

【问题讨论】:

  • 例如只需在 word 的每一侧留出空格,或使用\bword\b

标签: javascript string split


【解决方案1】:

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

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

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

【讨论】:

  • 如果单词用逗号分隔怎么办?
  • 如果单词后面有逗号,这将不起作用
  • .includes() 适用于字符串和数组,因此不需要 .split()
  • @adiga OP 没有要求分离,
  • @Scott Marcus 是的,它适用于字符串,但他想匹配整个单词。并且包含在字符串不匹配整个单词
【解决方案2】:

你可以将.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() 将其删除(如this 答案所示),然后使用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"));

【讨论】:

  • 对我来说似乎是一个很好的答案。不知道为什么人们不给他们 2 美分就投反对票。点赞。
  • @MarciaOng 谢谢 :) 很高兴我不是唯一一个认为 -1 不合理的人
  • @NickParsons 很好的答案。人们在投票前应该阅读和理解。这正是我想要的。
【解决方案3】:

这被称为regex - regular expression

当您需要解决这些问题时,您可以使用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'));

【讨论】:

  • 在以句点结尾的字符串上失败。例如“坚持下去”。
【解决方案4】:

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

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

此外,some 方法非常有效,因为如果 any 谓词为真,它将返回真。

【讨论】:

  • 当它有 !,.,;等等?
  • @epascarello 感谢您的精彩评论!我已经编辑了我的答案。
【解决方案5】:

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

【讨论】:

  • 或更好地使用正则表达式
  • @Aarif 也是一个很好的方法。
【解决方案6】:

一个简单的版本可能只是在空格上拆分并在结果数组中查找单词:

"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,\?\,\.!]+/)

【讨论】:

    【解决方案7】:

    我会做以下假设:

    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."));

    【讨论】:

      【解决方案8】:

      试试下面的 -

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

      【讨论】:

        猜你喜欢
        • 2011-03-29
        • 2020-09-20
        • 2018-08-25
        • 2010-12-19
        • 2016-01-25
        相关资源
        最近更新 更多