1

所以,我是 JavaScript 的新手。我现在正在使用 Codeacedemy 教程练习,它让我创建了一个程序,可以在一串文本中找到我的名字。但是,我意识到,如果我使用与我相似的名称,它也会返回另一个名称。我可以使用什么方法或如何优化代码以使其仅匹配字符串中的确切名称?

这是代码:

/*jshint multistr:true */

var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code";
var myName = "Zachary";
var hits = [];
for (var i = 0; i < text.length; i++){
    if (text[i] == 'Z') {
        for (var j = i;j < (i + myName.length); j++) {
            hits.push(text[j]);
        }
    }
}
if (hits === 0) {
    console.log("Your name was not found!");
}
else {
    console.log(hits);
}
4

7 回答 7

4

您可以String.split空格处的字符串以创建一个单词数组,然后根据您的测试字符串检查每个单词,从而防止子字符串中的匹配。(有一个替代循环while

Javascript

var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code",
    myName = "Zachary",
    hits = 0,
    array = text.split(/\s/),
    length = array.length,
    i = 0;

while (i < length) {
    if (myName === array[i]) {
        hits += 1;
    }

    i += 1;
}

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

jsfiddle 上

或者,如果你真的想通过循环检查字符串来获得乐趣,那么你可以做这样的事情。

Javascript

var text = "Zachary Hello my name is Zachary Sohovich. I'm a 20 year old dude from ZacharySouthern California and I loZacharyve to code Zachary",
    textLength = text.length,
    myName = "Zachary",
    nameLength = myName.length,
    check = true,
    hits = 0,
    i = 0,
    j;

while (i < textLength) {
    if (check) {
        if (i !== 0) {
            i += 1;
        }

        j = 0;
        while (j < nameLength) {
            if (text.charAt(i + j) !== myName.charAt(j)) {
                break;
            }

            j += 1;
        }

        if (j === nameLength && (/\s/.test(text.charAt(i + j)) || i + j === textLength)) { 
            hits += 1;
            i += j;
        }
    }

    i += 1;
    check = /\s/.test(text.charAt(i));
}

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

jsfiddle 上

注意:还有许多其他可能的解决方案可以为您做同样的事情。

于 2013-06-17T18:27:02.850 回答
3

你不需要做所有这些事情。

只需使用以下代码找到您的名字

if(text.indexOf(myName) !== -1){
  console.log('Found');
}

如果它是您想要查找的总出现次数

var count = text.match(/Zachary/g).length; 
console.log(count)
于 2013-06-17T18:10:02.060 回答
3

**

for(var i = 0; i < text.length ; i++){
    if(text[i] === "Z"){
        var getText = text.substring(i, i + myName.length);
        if(getText === myName)
        {
            for(var j = i; j < (myName.length + i); j++){
                hits.push(text[j]);
                }
            }
        }
    }

**

它会做......简单的一个。

于 2015-06-23T06:13:00.043 回答
1

这是我那节课的增强版。

/*jshint multistr:true */
var text = "Anastasius is known to have had a brother named Flavius Paulus, who served \
asRoman consul in 496. A sister-in-law, known as Magna, was mother to Irene and  \
mother-in-law to Olybrius. This Olybrius was son of Anicia Juliana and Areobindus \
Dagalaiphus Areobindus. The daughter of Olybrius and Irene was named Proba. She \
married Probus and was mother to a younger Juliana. This younger Juliana married another \
Anastasius and was mother of Areobindus, Placidia, and a younger Proba. Another nephew \
of Anastasius was Flavius Probus, Roman consul in 502. Caesaria, sister of Anastasius, \
married Secundinus. They were parents to Hypatius and Pompeius. Flavius Anastasius \
Paulus Probus Moschianus Probus Magnus, Roman Consul in 518 also was a great-nephew of \
Anastasius. His daughter Juliana later married Marcellus, a brother of Justin II. The \
extensive family may well have included viable candidates for the throne.";

var textAsWords = text.split(/\s/);

var myName = "Anastasius";

var hits = [];

for (var i = 0; i < textAsWords.length; i++) {
    if (myName === textAsWords[i]) {
        hits.push(textAsWords[i]);
    }
}

if (hits === 0) {
    console.log("Your name was not found!");
} else {
    console.log(hits);
}
于 2014-11-13T08:10:45.493 回答
0

这就是我想出的,与原始练习保持接近。

这包括将文本中的每个字母与名称的第一个字符进行比较。在找到该字符时,您必须将它和后面的任何字符添加到数组中,仅当字符数等于名称中的字母数时才停止。

接下来,要求学生改进代码,使其仅添加与确切名称匹配的字母。因为最初的练习没有使用空格或在一个完整的字母字符串中搜索名称的出现,所以我也没有。

/*jshint multistr:true */
var text = "olleboleYntke Mchael MichaetMichael S1knol E E rin oef goblinMichael kdmS3ksMichael K  elkekeerifdlkùYnyslght MichaelSerind";
myName = "Michael";
var hits = [];
var getCharName = function(namePos) {
  charName = myName[namePos];
};

for (i = 0; i <= text.length; i++) {
  namePos = 0;
  getCharName(namePos);
  if (text[i] === charName) {
    var letterMatch = false;
    for (j = 0; j < myName.length; j++) {
      getCharName((namePos + j));
      if (text[(i + j)] === charName) {
        letterMatch = true;
      } else {
        letterMatch = false;
      }
    }
    if (letterMatch === true) {
      for (j = 0; j < myName.length; j++) {
        hits.push(text[(i + j)]);
      }
    }
  }
}
if (hits === 0) {
  console.log("Your name was not found!");
} else {
  console.log(hits);
}

于 2015-02-04T15:18:35.327 回答
0

我也在做同样的练习,这就是我的答案。

该方法首先找到与 myName 的第一个字母匹配的内容。当我们找到匹配项时,我们会在其上放置一个 X 标记并向下运行文本以查看是否存在完全匹配项。如果完全匹配,我们返回 X 标记并将正确长度的文本放入输出数组“hits”。将所有字母放入数组后,我们返回 X 标记以继续处理其余文本。

如果我们没有完全匹配,我们返回到我们的 X 点并继续寻找与 myName 的第一个字母的匹配。

var text = "HahahnhahahahnhaHahahahahahahahahahahahaHahahahahahahahahahaHahahahahahnhaHahnhahahahahahahahahaHahaha"
var myName = "Hahn"

var hits =[] //the output will be an array

for(i=0; i<text.length; i++){ 
    var m = 0; 

    if(text[i] === myName[0]){ 
        for (j=0; j<myName.length; j++){ 
            if (text[i+j] !== myName[m]){ 
                break
            }
            m++; 
            if (m === myName.length){
                for (n=0; n<myName.length; n++){
                    hits.push(text[i+n]);
                }
            }
        }
    }
}

console.log(hits)
于 2015-05-13T02:29:54.537 回答
0

找到您的姓名的最短方法是使用.match以下示例:

var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from 
Southern California and I love to code";

var nameCheck = text.match(/zachary/gi)
console.log(nameCheck)

请注意,您的名字后面的gi告诉控制台记录所有匹配项,而不管要使用的大小写。您还可以通过将gi替换为g.match来区分大小写。

于 2017-02-12T22:08:26.017 回答