Tags
Asked 3 years ago
16 Jun 2021
Views 274
Emery

Emery posted

Check whether an input string contains a number in javascript

Check whether an input string contains a number in javascript
sandip

sandip
answered Apr 27 '23 00:00

To check whether an input string contains a number in JavaScript, you can use regular expressions and the test() method.

Here's an example:

javascript
Copy code
const str1 = "abc123def";
const str2 = "abcdef";
const hasNumber = /\d/.test(str1);
console.log(hasNumber); // Output: true
console.log(/\d/.test(str2)); // Output: false
In this example, the regular expression /\d/ matches any digit (\d) in the string. The test() method returns true if the regular expression matches any part of the string, and false otherwise.

You can also use the match () method to extract the number from the string as shown in the previous answer, and check if it returns a truthy value:



const str1 = "abc123def";
const str2 = "abcdef";
const number = str1.match(/\d+/);
const hasNumber = !!number; // double negation to convert to boolean
console.log(hasNumber); // Output: true
console.log(!!str2.match(/\d+/)); // Output: false

In this example, we use match () to extract any numbers in the string str1. If there are no numbers, the match () method will return null , which will be converted to false by the double negation (!!) operator. If there are numbers, the match () method will return an array, which will be converted to true .
Post Answer