Javascript 如何在字符串中查找单词?

Javascript 如何在字符串中查找单词?,javascript,Javascript,挑战是“查找Waldo”。我试图找出如何在函数/字符串中查找单词。“返回字符串‘Waldo’开始位置的索引。” 要完成的简单任务: function findWaldo(str) { return str.indexOf("waldo"); //the string you are looking for } 这一点解释得很好。应该有一个可以轻松实现的库,比如string.indexOf,但您可以使用此算法手动完成: int count = 0; string yourText = "

挑战是“查找Waldo”。我试图找出如何在函数/字符串中查找单词。“返回字符串‘Waldo’开始位置的索引。”

要完成的简单任务:

function findWaldo(str) {
    return str.indexOf("waldo"); //the string you are looking for
}

这一点解释得很好。

应该有一个可以轻松实现的库,比如
string.indexOf
,但您可以使用此算法手动完成:

int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";

for (int x = 0; x < yourText.Lenght; x++)
{
    if(yourText[x] == toSearch[0])
        if((count + 1) == toSearch.Lenght)
            return x;
    else
        count = 0;

   //here we'd say ehh there's not Waldo on the string
}
int count=0;
string yourText=“这是waldo?”;
字符串toSearch=“waldo”;
对于(int x=0;x
您是否尝试过搜索?这是许多语言实现的一个概念,称为
indexOf
,返回iterable中某个字符串或元素的索引。也许你应该先用谷歌搜索一下。
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";

for (int x = 0; x < yourText.Lenght; x++)
{
    if(yourText[x] == toSearch[0])
        if((count + 1) == toSearch.Lenght)
            return x;
    else
        count = 0;

   //here we'd say ehh there's not Waldo on the string
}