如何在字符串中搜索字符并输出字符出现的每个地方的索引? (JavaScript)的

时间:2012-10-28 21:22:07

标签: javascript string character document indexof

我明白了,谢谢。我需要将身体移动到html。更改了正文部分中的一些标记。

            }

            else
            {
                window.alert ("You entered an invalid character (" + enterLetter + ") please re-enter");
                secondPrompt();
            }

        }

</script>

<body onload = "firstPrompt();">

    <h2>
        Word Checker
    </h2>

    </body>
    </html>

2 个答案:

答案 0 :(得分: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 * /

答案 1 :(得分:0)

递归使用indexOf

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(根据上一个问题进行了一些调整)