You can easily check the string contains a number or numeric value by JavaScript match method with regular expression.
We’ll use the match method with regular expressions for numbers ([0-9]). If a match is found we’ll show output that string contains a number, if a match is not found we show output that the string does not contain a number.
Take a look at the code below:
JavaScript
// String does not contain a numeric value.
let string = "hello welcome to maketechstuff.com";
console.log("String: ", string);
if (string.match(/[0-9]/g)) {
console.log("Output: String contain a number");
} else {
console.log("Output: String does not contain a number.");
}
Output:
Now let's add number inside a string an see the output.
JavaScript
// String contain a numeric value.
let string = "Thanks 4 visiting maketechstuff.com";
console.log("String: ", string);
if (string.match(/[0-9]/g)) {
console.log("Output: String contain a number");
} else {
console.log("Output: String does not contain a number.");
}
Output:
So that's how you can check if the string contains the numbers or not using JavaScript. Feel free to leave any questions or suggestions in the comments below.
You may like:
- How to extract the numbers present in a string using JavaScript.
- How to remove the numeric values from a string using JavaScript.
- How to check if string contain the special character using JavaScript.
Share your thoughts.