EN
JavaScript - check if character is digit
11
points
In this short article, we would like to show how to check if the character is a digit using JavaScript.
Quick solution:
const DIGIT_EXPRESSION = /^\d$/;
const isDigit = (character) => {
return character && DIGIT_EXPRESSION.test(character);
};
Practical example
// ONLINE-RUNNER:browser;
const DIGIT_EXPRESSION = /^\d$/;
const isDigit = (character) => {
return character && DIGIT_EXPRESSION.test(character);
};
// Usage example:
// digits
console.log(isDigit('0')); // true
console.log(isDigit('5')); // true
console.log(isDigit('9')); // true
// letters
console.log(isDigit('a')); // false
console.log(isDigit('z')); // false
console.log(isDigit('A')); // false
console.log(isDigit('Z')); // false
// other
console.log(isDigit('10')); // false
console.log(isDigit('ab')); // false
console.log(isDigit('😎')); // false
console.log(isDigit('-')); // false
console.log(isDigit('.')); // false
console.log(isDigit('+')); // false
console.log(isDigit('*')); // false
Optimal solution
Note: this solution is many times faster than regular expression based solution.
// ONLINE-RUNNER:browser;
const isDigit = (character) => {
if (character.length === 1) {
const code = character.codePointAt(0);
return 47 < code && code < 58;
}
return false;
};
// Usage example:
// digits
console.log(isDigit('0')); // true
console.log(isDigit('5')); // true
console.log(isDigit('9')); // true
// letters
console.log(isDigit('a')); // false
console.log(isDigit('z')); // false
console.log(isDigit('A')); // false
console.log(isDigit('Z')); // false
// other
console.log(isDigit('10')); // false
console.log(isDigit('ab')); // false
console.log(isDigit('😎')); // false
console.log(isDigit('-')); // false
console.log(isDigit('.')); // false
console.log(isDigit('+')); // false
console.log(isDigit('*')); // false