Reputation: 155
I'm making a calculator app, I added an event listener to the document to listen to number keypresses, like so:
function listenForKeyPress() {
// add document event listener for all key presses
document.addEventListener('keyup', (e) => {
// check to see if the keypress was a number
if (/[0-9-+-\--.]/g.test(e.key)) {
// check to see if the input is not already focused
if (document.activeElement !== input) {
// focus element
input.focus();
// focus value
input.value += e.key;
}
}
})
}
// call function
listenForKeyPress();
The problem is when I refresh the page using F5 I get F5 typed into the input element, like so:
How can I prevent this from happening, thanks in advance.
Upvotes: 1
Views: 240
Reputation: 11485
I usually use isNaN(+variable)
as a check for a number in string. Regexp is way too expensive for a task this simple.
['-5', '5', 'F5', ' 5'].forEach(value => {
const valueAsNumber = +value;
console.log(`"${value}" is ${isNaN(valueAsNumber) ? 'not' : ''} a number. (${valueAsNumber})`);
})
Upvotes: 0
Reputation: 26360
I think you can modify your regex like this :
[0-9-+-\--.]
is weird, as it matches -
twice, and also the range "+" to "-" (char code 43 to 45). I think you want to prefer [\d-+*\/.]
to match either a digit (\d
), one of the operators +-*/
or the dot.Which gives :
const regex = /^[\d-+*\/.]$/;
regex.test("F5"); // false
regex.test("a"); // false
regex.test("5"); // true
regex.test("+"); // true
Upvotes: 2