如何在字符串中搜索字符并输出该字符出现的每个位置的索引?(Javascript)
我知道了,谢谢你。我需要将主体移动到html。更改了正文部分中的一些标记如何在字符串中搜索字符并输出该字符出现的每个位置的索引?(Javascript),javascript,string,character,document,indexof,Javascript,String,Character,Document,Indexof,我知道了,谢谢你。我需要将主体移动到html。更改了正文部分中的一些标记 } 其他的 { window.alert(“您输入了无效字符(“+enterLetter+”),请重新输入”); secondPrompt(); } } 查字器 您可以在每次找到匹配项时增加indexOf- function indexFind(string, charac){ var i= 0, found= []; while((i= string.indexOf(charac, i))!= -1)
}
其他的
{
window.alert(“您输入了无效字符(“+enterLetter+”),请重新输入”);
secondPrompt();
}
}
查字器
您可以在每次找到匹配项时增加indexOf-
function indexFind(string, charac){
var i= 0, found= [];
while((i= string.indexOf(charac, i))!= -1) found.push(i++);
return found;
}
indexFind('o')强>
/*返回值:(数组)
6,22,48
*/递归使用:
function findMatches(str, char) {
var i = 0,
ret = [];
while ((i = str.indexOf(char, i)) !== -1) {
ret.push(i);
i += char.length; //can use i++ too if char is always 1 character
};
return ret;
}
代码中的用法:
var matches = findMatches(enterWord, enterLetter);
if (!matches.length) { //no matches
document.write ("String '" + enterWord + "' does not contain the letter '" + enterLetter + ".<br />");
} else {
for (var i = 0; i < matches.length; i++) {
document.write ("String '" + enterWord + "' contains the letter '" + enterLetter + "' at position " + matches[i] + ".<br />");
}
}
var matches=findMatches(enterWord,enterLetter);
如果(!matches.length){//没有匹配项
document.write(“字符串”'+enterWord+“'不包含字母'+enterLetter+””
);
}否则{
对于(var i=0;i ”位置的字母“'+enterLetter+”;
}
}
(对上一个问题进行了一些调整)真是太好了,你在推送过程中用post增量进一步缩短了我的代码1行+1.尽管如此,由于OP是从JS开始的,我不会省略可选的大括号。更简短的是:
while(~(I=string.indexOf(charac,I))
正是我想要的。非常感谢你!
var matches = findMatches(enterWord, enterLetter);
if (!matches.length) { //no matches
document.write ("String '" + enterWord + "' does not contain the letter '" + enterLetter + ".<br />");
} else {
for (var i = 0; i < matches.length; i++) {
document.write ("String '" + enterWord + "' contains the letter '" + enterLetter + "' at position " + matches[i] + ".<br />");
}
}