JavaScript Code


How to check if string starts with a digit in JavaScript?


Check if string starts with a digit

Given a string, check if the string starts with a digit, using JavaScript.

Solution

To check if given string str starts with a digit using JavaScript, call test() method on the regular expression /^\d/ and pass the given string as argument to the method.

/^\d/.test(str)

The test() method returns true if the given string str starts with a digit, or false otherwise. We can use this expression as a condition in if-else statement.

Program

1. Given a string str. Check if this string starts with a digit.

var str = '24 apples';
if ( /^\d/.test(str) ) {
    console.log('string starts with digit');
} else {
    console.log('string does not start with digit');
}

Since the string contains digit as its first character, if-block must run.

2. Given a string str. This string does not start with a digit. Check programmatically if this string starts with a digit.

var str = 'hello 24 apples';
if ( /^\d/.test(str) ) {
    console.log('string starts with digit');
} else {
    console.log('string does not start with digit');
}

Since the string does not contain digit as its first character, else-block must run.