Check a String for Numbers in JavaScript

Jun 27, 2022

To check if a string contains a number in JavaScript, there are two approaches.

Using a Regular Expression

You can use a regular expression in combination with the test() function to confirm if there is a number in the string. The \d RegExp metacharacter matches any digit 0-9.

const example = 'Dial 555-555-5555 for a free consultation today!';
/\d/.test(example); // true

const example2 = 'Hawaii Five-O';
/\d/.test(example2); // false

The Iterative Approach

Another approach is to convert the string into an array and use the Array.find() function. If the string contains a digit, find() will return a truthy value. Otherwise, find() will return undefined.

const example = 'Dial 555-555-5555 for a free consultation today!';
[...example].find(char => char >= '0' && char <= '9'); // 5

const example2 = 'Hawaii Five-O';
[...example2].find(char => char >= '0' && char <= '9'); // undefined

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!