Languages
[Edit]
EN

JavaScript - check if character is digit

11 points
Created by:
starcraf35
754

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

 

See also

  1. JavaScript - check if string contains only digits 

Alternative titles

  1. JavaScript - isDigit function
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join