2012-10-28 65 views

回答

0

使用​​递归:

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

Live Demo

Full source(与你最后一个问题的一些调整)

+0

正是我在找的东西。非常感谢! – user1781453

2

您可以每次增加的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 */

+0

该死的不错,你缩短了我的代码1行进一步推后内部增量。 +1。尽管OP从JS开始,但我不会忽略可选的大括号。 –

+0

甚至更​​短:'while(〜(i = string.indexOf(charac,i)))' – KooiInc

相关问题