如何在javascript中检查字符串是否包含WORD? [重复]


记忆只剩空城
2025-03-18 02:31:01 (3天前)


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

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

例如,如果我应用“on”搜索…

6 条回复
  1. 0# 浮华丶 | 2019-08-31 10-32



    您可以使用

    .includes()

    并检查这个词。要确保它是一个单词而不是另一个单词的一部分,请验证您找到它的位置后面是空格,逗号,句点等,并且还有其中一个单词。


  2. 1# 哦豁 | 2019-08-31 10-32



    我会采用以下假设:




    1. 单词句子的开头总是有一个尾随空格。


    2. 句子末尾的单词总是有前面的空格。


    3. 句子中间的单词总是有一个尾随和前面的空格。

    4. </醇>


      因此,我会编写如下代码:








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

      2. console.log(containsWord(“test”, This is a test of the containsWord function.”));






  3. 2# 坚挺的阿袁 | 2019-08-31 10-32



    尝试以下方法 -








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






  4. 3# 一生流水 | 2019-08-31 10-32



    使用

    Array.prototype.includes


    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes








    1. console.log(“keep it on the table”.toLowerCase().split(“ “).includes(“on”)); // true
      console.log(“phones are good”.toLowerCase().split(“ “).includes(“on”)); // false







    或者您可以使用正则表达式。


  5. 4# 苞米地里的蒙面妖 | 2019-08-31 10-32



    一个简单的版本可能只是在空白上拆分并查看生成的数组:




    1. phones are good”.split(“ “).find(word => word === on”) // undefined

    2. keep it on the table”.split(“ “).find(word => word === on”) // “on”

    3. </code>


    这只是按空格分割,但是当你需要解析文本时(取决于你的输入),你会遇到比空格更多的单词分隔符。在这种情况下,您可以使用正则表达式来计算这些字符。
    就像是:




    1. Phones are good, arent they? They are. Yes!”.split(/[\s,\?\,.!]+/)

    2. </code>

登录 后才能参与评论