在不使用match()的情况下查找确切的字符串

时间:2015-07-21 08:48:37

标签: javascript

这是我的代码。我试图匹配已存储在命中数组[]中的确切单词。我只想打印myName变量的确切内容。我们可以不使用match()方法吗?

var text = "Blaaah Bllaaah Bllaaah Paolo Blahhh Paaolo paolo";

var myName = "Paolo";

var hits = [];

for(var x=0; x<text.length; x++){
        if(text[x]===("P")){

            for(var i = x; i<(myName.length + x); i++){
                hits.push(text[i]);
                }
            }


    }

    if(hits.length === 0 ){
        console.log("Your name wasn't found");    
        }else{



            console.log(hits);

        }

5 个答案:

答案 0 :(得分:1)

怎么样:

var text = "Blaaah Bllaaah Bllaaah Paolo Blahhh Paaolo paolo";

var myName = "Paolo";

var textArray = text.split(' ');
var hits = textArray.filter(function(value){ return value === myName; });

if(hits.length === 0 ){
  console.log("Your name wasn't found");    
}else{
  console.log(hits);
}

该解决方案使用array.filter()查找完全匹配。

答案 1 :(得分:0)

一个简单的条件:

if(text.indexOf(myName) != -1) {
  // name found
}

或者如果你想要一个单词匹配,只需将单词列表拆分成一个单词数组:

if(text.split(' ').indexOf(myName) != -1) {
  // name found
}

现场观看:

var text = "Blaaah Bllaaah Bllaaah Paolo Blahhh Paaolo paolo";

function findName(word) {
  var name = prompt('Enter name:');
  if (!name) 
    return;
  var t = word ? text.split(' ') : text;
  if(t.indexOf(name) != -1) {
    alert('Name ' + name + ' found!');
  }
  else {
    alert('Name ' + name + ' NOT found!');
  }
  findName(word);
}
<button onclick="findName()">String match</button>
<button onclick="findName(true)">Word match</button>

答案 2 :(得分:0)

尝试以下方法:

var text = "Blaaah Bllaaah Bllaaah Paolo Blahhh Paaolo paolo";

var myName = "Paolo";

var foundArray = text.split(" ").filter(function(e){ return e == myName });

if (foundArray.length) { /* name is found */ }

答案 3 :(得分:-1)

您可以使用indexOf方法:

"Blaaah Bllaaah Bllaaah Paolo Blahhh Paaolo paolo".indexOf('Paolo') =&gt; 23

"Blaaah Bllaaah Bllaaah Paolo Blahhh Paaolo paolo".indexOf('Paolooo') =&gt; -1

答案 4 :(得分:-1)

您可以使用完全匹配的简单事实: if ("abc" == "abc")

首先,您要创建一个阵列,以便与搜索匹配。然后,您只需将所有这些数组元素与上面的代码进行比较。结果将是这样的:

var haystack = "Blaaah Bllaaah Bllaaah Paolo Paolo Blahhh Paaolo paolo";

var search = "Paolo";

// Create an array
var haystackArray = haystack.split(" ");
var hits =0;

// For each array element
for(var i = 0; i < haystackArray.length; i ++){
    // Check if this array element match exactly your search string
    if(search == haystackArray[i])
        hits++;
}
console.log(hits);