Reputation: 31
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
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);
Upvotes: 1
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).
Upvotes: 1