如何修复此程序,以便只搜索我的名字?

时间:2016-08-06 15:20:50

标签: javascript arrays string search

我正在学习 JavaScript ,我构建了这个程序,搜索以查找String中字母E的实例,而不是逐字逐句地存储到array,但现在当它找到类似字母E的实例时,它也输出类似的实例,在这种情况下我有Eddie和Eric。在这种情况下,我不希望它输出类似的Eric实例。我知道有一种hacky方法可以做到这一点,比如if(nameYouFound !== "myName")。但是我不喜欢它...在我学到这一点的网站上,它表示内置JavaScript,string方法可以提供帮助。你知道什么方法可以解决这个问题吗?

  

请不要回答JQuery,我正努力做得更好   的JavaScript ...

以下是代码段:

/*jshint multistr:true */
var text, myName, hits, i, j;
text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
myName = "Eddie";
hits = [];
for (i = 0; i < text.length; i++) {
  if (text[i] === "E") {
    for (j = i; j < (myName.length + i); j++) {
      hits.push(text[j]);
    }
  }
}

if (hits.length == 0) {
  alert("Your name was not found!")
} else {
  alert(hits);
}

3 个答案:

答案 0 :(得分:2)

根据您的标题,

  

如何修复此程序,以便只搜索我的名字?

我对你的问题的理解可以帮到你:

        var text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
	var myName = 'Eddie';

	if (text.search(myName)!== -1) {
		alert('Eddie found');
	} else {
		alert('Eddie not found');
	}

答案 1 :(得分:1)

这能帮到你找到你想要的东西

/*jshint multistr:true */
var text, myName, hits, i, j;
text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
myName = "Eddie";
var isFound=text.includes(myName);
var index= text.indexOf(myName);
if(isFound){
  alert("You name was found by using \"includes\" method");
}else{
  alert("You name was not found with \"includes\" method");
}
if(index>=0){
   alert("You name was found at "+ index +" by using \"indexOf\" method");
}else{
  alert("You name was not found with \"indexOf\" method");
}

答案 2 :(得分:1)

您可以对字符串使用内置的indexOf()方法。

var text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
var myName = "Eddie";
var hits = [];
var startIndex = text.indexOf(myName);
if (startIndex !== -1) { // myName exists in text
    for (var i = startIndex; i < startIndex + myName.length; ++i) {
        hits.push(text[i]);
    }
}
else {
    // Do whatever you want like.. 
    console.log("Not Found!")
}