JavaScript Code


How to check if string contains only numeric in JavaScript?


Check if string contains only numeric

Given a string, check if the string contains only numeric characters ( from 0 to 9), using JavaScript.

Solution

To check if given string str contains only numeric characters using JavaScript, call match() method on the given string and pass a regular expression that matches one or more numeric characters /^[0-9]+$/ as argument to the method.

str.match(/^[0-9]+$/)

The match() method returns true if the given string str contains only numeric, or false otherwise. We can use this expression as a condition in if-else statement.

Programs

1. Given a string str. Check if this string contains only numeric.

var str = '01245124512';
if ( str.match(/^[0-9]+$/) ) {
    console.log('string contains only numeric');
} else {
    console.log('string does not contain only numeric');
}

Since the string contains only numeric, if-block must run.

2. Given a string str. This string does contain some alphabets. Check programmatically if this string contains only numeric.

var str = '125412am8';
if ( str.match(/^[A-Za-z0-9]+$/) ) {
    console.log('string contains only alphanumeric');
} else {
    console.log('string does not contain only alphanumeric');
}

Since the string does not contain only numeric, else-block must run.