Javascript 中 indexOf 的替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13669212/
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
alternative to indexOf in Javascript
提问by Fahim Parkar
I have string as this is test for alternative
. What I want to find is location of for
. I know I could have done this using alert(myString.indexOf("for"))
, however I don't want to use indexOf
.
我有字符串作为this is test for alternative
. 我想找到的是for
. 我知道我可以使用 完成此操作alert(myString.indexOf("for"))
,但是我不想使用indexOf
.
Any idea/ suggestion for alternative?
任何想法/建议替代?
jsfiddle
提琴手
Again, I need this done by Javascriptonly. No jQuery.. sadly :(
同样,我只需要通过Javascript来完成。没有 jQuery .. 可悲的是 :(
回答by Barak
.search()?
"this is test for alternative".search("for")
>> 13
回答by koopajah
You could code your own indexOf ? You loop on the source string and on each character you check if it could be your searched word.
您可以编写自己的 indexOf 吗?您在源字符串和每个字符上循环,检查它是否可能是您搜索的单词。
An untested version to give you an idea:
一个未经测试的版本给你一个想法:
function myIndexOf(myString, word) {
var len = myString.length;
var wordLen = word.length;
for(var i = 0; i < len; i++) {
var j = 0;
for(j = 0; j < wordLen; j++) {
if(myString[i+j] != word[j]) {
break;
}
}
if(j == wordLen) {
return i;
}
}
return -1;
}