2

是否有内置的 JavaScript 字符串方法可以帮助我微调此代码以确保它只找到名称的完全匹配?

这是我的代码。

/*jshint multistr:true */

var text = "Sid quick brown fox jumps over the lazy dog ";
var myName = "Sid";
var hits = [];

for (var i=0; i< text.length; i++){
    if(text[i] === 'S'){
        for(var j=i; j < i + myName.length; j++){
            hits.push(text[j]);
        }
    }else{
        console.log("Your name wasn't found!")
    }

}
console.log(hits);
4

10 回答 10

5

所以这是另一个解决方案,使用 function match(),但更简单:

/*jshint multistr:true */
var text = "Hey, how are you doing Sanda? My name is Emily.\
Nice to meet you Sada. Where does your name come from, Sana?\
is Sanda a slavic name?";
/*var myName = "Sanda";
hits = [];

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

if ( hits.length === 0 ) "Your name wasn't found!";
else console.log(hits);*/

var hits = text.match(/Sanda/g);

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

语法是var <someVar> = <textToBeSearched>.match(/pattern/modifiers). 我的修饰符g是全局的(搜索整个模式)。

更多信息在这里: http ://www.w3schools.com/jsref/jsref_match.asp http://www.w3schools.com/js/js_regexp.asp

干杯!

于 2014-05-24T06:43:12.663 回答
2

OP 的示例来自 codecademy,所以如果有人正在寻找与Javascript 相关的答案:第 6/7 课,这就是我想出的:

/*jshint multistr:true */
var text = "How are you \
doing Sabe? What are you \
up to Sabe? Can I watch \
Sabe?";

var myName = "Sabe";

var hits = [];

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

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

 

然后,我决定像 OP 一样进行额外的挑战,即创建一个需要完全匹配的字符串。codecademy javascript 课程是为新手准备的,所以他们正在寻找的答案是使用for循环和广泛的if/else语句来给我们练习。

从学习曲线的角度来看的扩展版本:

/*jshint multistr:true */
var text = "The video provides a powerful way to help you prove \
your point. When you click Online video, you can paste in the \
embed code for the video you want to add. You can also type a \
keyword to search online for the video that best fits your document.";

var theWord = "video";
var hits = [];

for (var i = 0; i < text.length; i++) {
    if (theWord === text.substr(i,theWord.length)) {
         hits.push(i);
         i += theWord.length-1; 
    }
}

if (hits.length) {
    for (i = 0; i < hits.length; i++) {
        console.log(hits[i],text.substr(hits[i],theWord.length));
    }

} else {
    console.log("No matches found.");
}

 

然后match()@Sanda 提到了现实生活中的例子:

/*jshint multistr:true */

var text = "The video provides a powerful way to help you prove \
your point. When you click Online video, you can paste in the \
embed code for the video you want to add. You can also type a \
keyword to search online for the video that best fits your document.";

var hits = text.match(/video/g);


if ( hits.length === 0) {
    console.log("No matches found.");
} else {

    console.log(hits);
}

 

我希望这对 codecademy 的人们有所帮助!

于 2015-09-27T10:12:49.590 回答
1
var text = "Blah blah blah blah blah blah Hafeez \
blah blah blah Hafeez blah blah Hafeez blah blah \
blah blah blah blah blah Huzaif, Hazere";

var myName = "Hafeez";
var hits = [];

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

    }
}

if(hits === 0)
{
    console.log("Your name was'nt found");

}
else
{
    console.log(hits);
    console.log(hits.length);
}
于 2014-11-13T11:48:12.777 回答
1

使用它只匹配确切的名称,而不是部分名称。

var text = "Hello my name is Johny, are you Sandra, Sandra?";
var names = ["Sandra", "John"];

for (var i = 0; i < names.length; i++) {
  var re = new RegExp("\\b" + names[i] + "\\b", "g");
  document.write("Matches for " + names[i] + ": " + (text.match(re) ? text.match(re).length : 0) + "<br>");
}

\b表示正则表达式中的单词边界

于 2015-07-16T09:04:01.733 回答
1

在 Code Academy 的 Javascript 基础课程中也遇到过这个练习。

我的解决方案如下。很基本,但完成了工作。

var text = "There is a real risk of the British economy being harmed Olly which has the potential to create an environment in which businesses could go under and Olly jobs could be lost. The economic Oggle uncertainty was tangible yesterday as global financial markets lost Olly up to $2 Trillion USD value and the pound was at it’s lowest value for 30 years before recovering somewhat."

var myName = "Olly"
var hits = []

for (var i = 0; i < text.length; i++) {
    if (text[i] === "O" && text[i +1] === "l" && text [i +2] === "l" &&     text[i + 3] === "y") {
        for(var j = i; j < (myName.length + i); j++) {
            hits.push(text[j]);
        }
    }
}

if (hits.length === 0) {
    console.log("Your name wasn't found!");   
} else {
    console.log(hits);
}
于 2016-08-13T18:36:35.417 回答
0

您可以尝试使用正则表达式:

var text = "Sid quick brown fox jumps over the lazy dog ";
var myName = "Sid";

var re = new RegExp(myName);

re.exec(text);
// => ["Sid"]

或者如果你一定想要一个字符串方法:

myName.match(re);
于 2013-09-05T15:06:57.420 回答
0

无论如何继承一些更好的代码

check(0);

function check(start){
if ( text.subStr(start).indexOf(myName) >= 0 ){
hits++;
    check(text.subStr(start).indexOf(myName));
}
}
if (hits < 1 ){
    console.log("Your name wasn't found!")
}
console.log(hits);

仍然没有检查它是否有效,但它的一般想法

所以回答是“有一个内置的 Javascript 字符串方法可以帮助我(你)微调这个代码,以确保它只找到名称的完全匹配。”

于 2013-08-26T00:23:17.880 回答
0

我不知道这是否与其他一些答案完全不同,但这就是我在不使用 RegEx 的情况下所做的,并且仍然用所有出现的相关字符串填充数组变量。同样,我只使用了 substring() 添加的 String 方法来做到这一点,这使得这成为另一个可能的答案。希望这可以帮助:

var text = "blah bhlekm kdnclwi Christian blah blah, lots of blah in this text, blahChristian got one more Christian, and that's it.";
var myName="Christian";
var hits = [];
for (i=0; i<text.length; i++){
    if (text.substring(i, i+ myName.length) === myName){
            hits.push(text.substring(i, i+myName.length));
        }
    }

    if (hits.length == 0){
        console.log("Your name wasn't found!");
    }else{
        console.log("your name showed up " + hits.length + " times.");
    }
于 2013-10-29T12:52:17.373 回答
0

这是我自己的解决方案,使用 substring() 函数和 search() 函数,这是一个内置的 JavaScript 字符串方法,可以检查文本以查找您要查找的单词。成功后,它将返回该单词存在的文本位置,如果失败,则返回 -1 值。这只是另一种方法。

/*jshint multistr:true */
var text = "hey wassup mike? \
wanna play football with mike, maria and antonis?!??!??!?!";
var myName = "mike";
var hits = [];
var pos = text.search(myName);

while(pos !== -1) {
     for (var j = 0; j < myName.length; j++) {
            hits.push(myName[j]);
        }
    text = text.substring(pos+myName.length,text.length);
    pos = text.search(myName);
}

if(hits === "")
{
    console.log("Your name wasn't found!");
}
else 
{
    for (var h = 0; h < hits.length; h++) {
        console.log(hits[h]);
    }
}
于 2015-06-28T15:55:34.267 回答
0

这是使用 substr 的解决方案:

/*jshint multistr:true */

var text = "Lampe hinab la Samir licht schen er te recht. \
        Furchtete verodeten wo te Song flanierte \
        grundlich er Samir he. Bekam einem blank \
        da so schlo mu so.",
    myName = "Samir",
    hits = [];

for (var i = 0; i < text.length; i++) {
    if (text[i] === myName[0]) {
       var substr = text.substr(i, myName.length);
        if (substr === myName) {
           for (var j = i; j < i + myName.length; j++) {
               hits.push(text[j]);
           }
       }
   }
}
if (hits.length === 0) {
    console.log ("Your name wasn't found!");
} else {
    console.log (hits);
};
于 2016-02-24T12:01:50.320 回答