user3286750
user3286750

Reputation: 31

Something wrong with RegExp or the loop

I have to count how many times a letter has been pressed. I wrote the program (I have to use only JS), most of it, but I seem to have encountered a problem.

If the input from the keyboard is "w s s d", it will say that "letter w was pressed once" and "letter s was pressed 2 times". Letter D is not displayed at all. And, to be honest, I can't see what could be the problem.

for(index = 0; index< inputList.length; index++) {        
    if(str != null && patt.test(str) && inputList[index].trim().length > 0) {
        var match1 = str.match(new RegExp(inputList[index], "g"));                        
        if(match1 != null){

        output.innerHTML = output.innerHTML + ('<span>Letter ' + inputList[index] + " was pressed " + match1.length + " times</span><br/>");
        str = str.replace(new RegExp(inputList[index], "g"), '');
        }
    }
}

Here's the fiddle: code

Upvotes: 0

Views: 66

Answers (2)

sabof
sabof

Reputation: 8192

It's not really an answer. More of a question. All I did was add this while debugging, which should have no effect whatsoever. But it does, and tada, everything works.

patt.test(str);

FIDDLE

Upvotes: 1

Jerry
Jerry

Reputation: 71538

After printing the number of times, put this:

index = index + match1.length - 1;

This is because you are always increasing index by 1 even when keys are pressed more times, which means when you have w s s d, you're looping through indexes 0 1 2 instead of 0 1 3 (2 is skipped because s occurs twice).

fiddle edited

Upvotes: 1

Related Questions