匹配句子中的确切字符串

时间:2011-03-21 14:54:09

标签: javascript

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

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

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

我试过

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

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

3 个答案:

答案 0 :(得分:5)

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

我认为你应该使用单词边界来表达正则。

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

答案 1 :(得分:4)

使用javascript的String.indexOf()

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

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

// 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
  );
}

Oop,错误的文档参考。引用了array.indexOf

答案 2 :(得分:0)

ContainsExactString2只是比我更深入,'==='应该可以正常工作

<input id="execute" type="button" value="Execute" />

// Contains Exact String

$(function() {
    var s = "HeyBro how are you doing today";
    var a = "Hey";
    var b = "HeyBro";
    $('#execute').bind('click', function(undefined) {
        ContainsExactString(s, a);
        ContainsExactString(s, b);
    });
});

function ContainsExactString2(sentence, compare) {
    var words = sentence.split(" ");
    for (var i = 0; i < words.length; ++i) {
        var word = words[i];
        var pos = 0;
        for (var j = 0; j < word.length; ++j) {
            if (word[j] !== compare[pos]) {
                console.log("breaking");
                break;
            }
            if ((j + 1) >= word.length) {
                alert("Word was found!!!");
                return;
            }++pos;
        }
    }
    alert("Word was not found");
}

function ContainsExactString(sentence, compare) {
    var words = sentence.split(" ");
    for (var i = 0; i < words.length; ++i) {
        if(words[i] === compare) {
            alert("found " + compare);
            break;
        }
    }
    alert("Could not find the word");
    break;
}