javascript 字符串方法精确文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17153907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:18:23  来源:igfitidea点击:

string method exact text

javascriptstringmethodsexact-match

提问by sneakycrow

So, I am brand spanking new to JavaScript. I am practicing right now with a Codeacedemy tutorial, and it had me create a program that finds my name in a string of text. But, I realized that if I use a name thats similiar to mine, it will return the other name too. What method can I use or how can I refine the code so that it will only match the exact name in the string?

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

Here's the code:

这是代码:

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

回答by Xotic750

You could String.splitthe string at the white spaces to create an array of words and then check each word against your test string, thus preventing matches within a substring. (with an alternative loop while)

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

Javascript

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

On jsfiddle

jsfiddle 上

Or if you really want to have fun with checking the string by loops then you could do something like this.

或者,如果您真的想通过循环检查字符串来获得乐趣,那么您可以执行以下操作。

Javascript

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

On jsfiddle

jsfiddle 上

Note: there are a number of other possible solutions that will do the same for you.

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

回答by Nagarjun

You need not do all those stuff.

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

Just find your name with following code

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

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

If its the total number of occurrences you would like to find

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

var count = text.match(/Zachary/g).length; 
console.log(count)

回答by khaled4vokalz

**

**

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

**

**

It'll do... easy one.

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

回答by Anastasius

Here's my enhanced version of that lesson.

这是我那节课的增强版。

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

回答by M. Fellow

This is what I came up with, staying close to the original exercise.

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

This consisted of comparing each letter in the text to the first character of the name. On finding that character, you had to add it and anycharacters that followed into an array, only stopping when the number of characters were equal to the number of letters in the name.

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

Next, the student was asked to improve the code so it would only add letters matching the exact name. Because the original exercise did not use whitespace or searching for an occurence of the name in one complete string of letters, I did not either.

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

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

回答by Hahn Dong

I'm on the same exercise, and this is my answer.

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

The method first finds a match with the first letter of myName. When we find a match, we place a X marker on it and run down the text to see if there is a full match. If there is a full match, we return to the X marker and place the correct length of text into the output array "hits". After placing all the letters into the array, we return to the X marker to continue with the rest of the text.

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

If we don't have a full match, we return to our X spot and continue on to find a match with the first letter of myName again.

如果我们没有完全匹配,我们返回到我们的 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)

回答by user7554937

The shortest way of finding your name is to use .matchexample below:

查找您姓名的最短方法是使用.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)

Note that THE giafter your name this tells the console to log all matches irrespective of case to use. You can also use .matchto also be case sensitive by replacing giwith g.

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