在字符串中查找多个单词

时间:2014-12-14 07:16:19

标签: javascript string search

我试图在逗号分隔的日志中找到多个单词。我使用下面的代码,这段代码可以一次找到一个单词,但不能同时找到3个单词。

$log = "Left Side Turn, Left Side Road, No Turn, Left, Right Turn";
var currLog = $("#log").text();

var theName = "Left Side Road";      //this is what I'm searching for...

var currLogWords = currLog.split(/\b/);
        var hits = [];
        for (var i = 0; i < currlogWords.length; i++) {
            if (theName == currlogWords[i]) {
                hits.push(currlogWords[i]);
            }
        if (hits == 0) { do something } else { do other }

2 个答案:

答案 0 :(得分:0)

split()函数的参数决定了如何拆分字符串的内容。目前,您正在使用\b选择任何分词符(例如空格);只需将其更改为使用逗号,以便您只能使用逗号分割(您还需要在拆分后删除前导和尾随空格,以便删除每个以逗号分隔的项目周围出现的额外空格。)

答案 1 :(得分:0)

我不知道为什么你当前的代码应该有效,因为它currLogWordscurrlogWords,所以它应该给出currlogWords is not defined之类的错误。

搜索完整的字符串试试这个:

var log = "Left Side Turn, Left Side Road, No Turn, Left, Right Turn";
    var currLog = $("#log").text();

    var theName = "Left Side Road";      //this is what I'm searching for...

    var currLogWords = log.split(',');
            var hits = [];
            for (var i = 0; i < currLogWords.length; i++) {
                if (theName.trim() == currLogWords[i].trim()) {
                    hits.push(currLogWords[i]);
                }
            }
            if (hits == 0) { 
                console.log(hits.length); 
                } else { 
                    console.log(hits);
                    console.log(hits.length); 
                }