Check if a String Contains Numbers in JavaScript

Introduction

When working with JavaScript, it's not uncommon to need to determine if a string contains numbers, especially when you're taking input from a user or trying to parse text from another source, like a document.

In this Byte, we'll explore several ways to identify if a string contains numbers, using different JavaScript methods.

Using match() to Detect Numbers in a String

The match() method is a great tool in JavaScript for working with strings. It searches a string for a match against a regular expression, and returns the matches, as an Array object.

Here's how you can use match() to check if a string contains any numbers:

let str = "Hello, I am 25 years old.";
let hasNumbers = /\d/.test(str);

console.log(hasNumbers); // Outputs: true

In this example, /\d/ is a regular expression that checks if at least one digit (equivalent to [0-9]) exists. The test() method returns a boolean: true if the string contains a number, and false otherwise.

Identifying if a String Consists Solely of Numbers

Sometimes, you might need to check if a string consists solely of numbers. In this case, you can modify the regular expression used with the match() method.

let str = "12345";
let isOnlyNumbers = /^\d+$/.test(str);

console.log(isOnlyNumbers); // Outputs: true
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

In this example, ^\d+$ is a regular expression that matches a string that starts and ends with one or more digits. Thus, the test() method will return true only if the string consists solely of numbers.

Matching Numbers Separated by Characters

There are an infinite number of scenarios in which you'd need to check for the existence of both numbers and non-numerical characters. One such case is when you'd want to identify numbers that are separated by characters.

For instance, a date string like "12-30-2020" contains numbers, but they're separated by dashes. What if, as our input validation, we wanted to make sure that it had at least two consecutive numbers and a dash?

To handle this scenario, you can use the following code:

let str = "12-30-2020";
let hasNumbers = /\d{2}-/.test(str);

console.log(hasNumbers); // Outputs: true

Here, the \d{2} regular expression will check for at least two consecutive digits, and the - will ensure that a dash follows the two digits.

Conclusion

In this Byte, we saw a few ways to check if a string contains numbers using JavaScript. We've seen how to use the match() method with different regular expressions to detect numbers in a string, check if a string consists solely of numbers, and even identify numbers separated by characters.

Last Updated: August 15th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms