如何使用indexOf或JavaScript中仅包含完全匹配的单词

时间:2019-02-11 12:51:58

标签: javascript node.js

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

    let str = "Widget test";

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

它将打印找到它,因为它不匹配整个单词,仅匹配子字符串。如果只有匹配项是小部件,如何将其返回找到?

但是我想要的是:

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

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

4 个答案:

答案 0 :(得分:2)

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

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

在您的示例中:

let str = "Widget";

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

答案 1 :(得分:1)

您也可以尝试这个。

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

答案 2 :(得分:1)

在尝试回答此问题时,提供了正确的答案。而且还不清楚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

答案 3 :(得分:0)

如果找到的字符串比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!' ); 
}