2012-10-28 129 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

相關問題