匹配句子中的确切字符串

daz*_*zle 4 javascript

如何精确匹配句子中的给定字符串。

例如,如果句子是var句子=“ Google Wave基本上是捕获通信的文档”

而给定的字符串是var inputString =“ Google Wave”。我需要检查上述句子中Google Wave的确切存在并返回true或false。

我试过了

if(sentence.match(inputString)==null){
            alert("No such word combination found.");
        return false;
        }
Run Code Online (Sandbox Code Playgroud)

即使有人输入“ Google W”,此方法也有效。我需要找到完全匹配的方法。请帮忙

Tho*_* Li 6

使用进行搜索时,OP希望返回false Google W

我认为您应该使用单词边界进行正则表达式。

http://www.regular-expressions.info/wordboundaries.html

样品:

inputString = "\\b" + inputString.replace(" ", "\\b \\b") + "\\b";
if(sentence.toLowerCase().match(inputString.toLowerCase())==null){
    alert("No such word combination found.");
}
Run Code Online (Sandbox Code Playgroud)


Bra*_*tie 5

使用javascript的String.indexOf()

var str = "A Google wave is basically a document which captures a communication";
if (str.indexOf("Google Wave") !== -1){
  // found it
}
Run Code Online (Sandbox Code Playgroud)

对于不区分大小写的比较,并使其变得更容易:

// makes any string have the function ".contains([search term[, make it insensitive]])"
// usage:
//   var str = "Hello, world!";
//   str.contains("hello") // false, it's case sensitive
//   str.contains("hello",true) // true, the "True" parameter makes it ignore case
String.prototype.contains = function(needle, insensitive){
  insensitive = insensitive || false;
  return (!insensitive ?
    this.indexOf(needle) !== -1 :
    this.toLowerCase().indexOf(needle.toLowerCase()) !== -1
  );
}
Run Code Online (Sandbox Code Playgroud)

糟糕,文档参考错误。正在引用array.indexOf