【问题标题】:How to match only the exact word using indexOf or includes in JavaScript如何使用 indexOf 或在 JavaScript 中仅匹配确切的单词
【发布时间】:2019-02-11 12:51:57
【问题描述】:

我只想使用 javascript 搜索字符串中的特定单词。但是使用 match、indexOf 或 include 不能正常工作。假设

    let str = "Widget test";

   if (~str.indexOf("Widge")) {
    console.log( 'Found it!' );
    }

它会打印找到它,因为它不匹配整个单词,只匹配子字符串。如果只有匹配项是 Widget,我如何将其返回到 find

但我想要的是:

如果输入字符串 = 小部件,则输出 = true

如果输入字符串 = Widge,输出 = false

【问题讨论】:

  • 有哪些可能的输入和输出?
  • @JamesCoyle 已编辑,立即查看
  • 只使用str == "Widget",如果你想匹配任何单词使用str.split(/\s+/)在数组上使用indexOf。
  • 你的支票是错误的,.. 试试 -> ~"Widge".indexOf("Widget")
  • 有什么理由支持按位运算符而不是String.contains

标签: javascript node.js


【解决方案1】:

要匹配确切的单词,您必须使用正则表达式。

/\bWidget\b/ 将匹配整个单词。

在你的例子中:

let str = "Widget";

if (str.search(/\bWidget\b/) >= 0) {
 console.log( 'Found it!' );
}

【讨论】:

  • RegEx 非常适合这类事情,但是 -> you will have to,这不是真的。
  • 你是对的,这只是解决这个问题的一种方法:)
【解决方案2】:

你也可以试试这个。

let str = "Widget test";
if(str.split(" ").indexOf('Widge') > -1) {
    console.log( 'Found it!' );
}

【讨论】:

    【解决方案3】:

    在尝试回答此问题时,提供了正确答案。而且还不清楚OP到底想要什么......

    ...所以同时我写了这个糟糕的~hack~解决方案:

    const matchType = (source = '', target = '') => {
      const match = source.match(target) || [];
      return (!isNaN(match.index) && !!~match.index)
        ? match.input === target ? 'complete' : 'partial'
        : 'none';
    };
    
    console.log(matchType('foo', 'bar'));
    console.log(matchType('foo', 'fo'));
    console.log(matchType('foo', 'foo'));

    现在您可以拥有三种不同类型的比赛,不是很酷吗? :D

    【讨论】:

      【解决方案4】:

      如果未找到字符串而不是 indexOf 将返回 -1,因此您可以检查索引不等于 -1 而不是找到的字符串

      function match(){
      var test = "Widget test";
      if (test.indexOf("widget")!= -1) {
        alert( 'Found it!' );
      }else{
      alert( 'Sorry,not Found it!' );
      }
      }
      <!DOCTYPE html>
      <html>
      <body>
      
      <button type="button" onclick="match()">Click Me!</button>
      
      </body>
      </html>
      let str = "Widget test";
      
      if (str.indexOf("wi")!= -1) {
        console.log( 'Found it!' ); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-16
        • 1970-01-01
        • 1970-01-01
        • 2019-10-23
        • 1970-01-01
        • 2016-11-16
        • 1970-01-01
        • 2014-09-02
        相关资源
        最近更新 更多