user1781453
user1781453

Reputation: 25

How to search for a character in a string and output the index of every place that character appears? (Javascript)

I figured it out, thank you. I need to move the body to the html. Changed some tags in the body section.

            }

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

        }

</script>

<body onload = "firstPrompt();">

    <h2>
        Word Checker
    </h2>

    </body>
    </html>

Upvotes: 1

Views: 148

Answers (2)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70139

Using indexOf recursively:

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;
}

Usage in your code:

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 (with some tweaks from your last question)

Upvotes: 0

kennebec
kennebec

Reputation: 104760

You can increment indexOf each time you find a match-

function indexFind(string, charac){
    var i= 0, found= [];
    while((i= string.indexOf(charac, i))!= -1) found.push(i++);
    return found;
}

indexFind('It\'s more like it is today, than it ever was before','o');

/* returned value: (Array) 6,22,48 */

Upvotes: 2

Related Questions