Check if String starts with Number using JavaScript


Borislav Hadzhiev

Last updated: Oct 27, 2021


Photo from Unsplash

Check if String starts with Number #

To check if a string ends with a number, call the test() method on the following regular expression - /^\d/. The test method will return true if the string starts with a number, otherwise false will be returned.

// ✅ Check if string starts with number ✅ function startsWithNumber(str) { return /^\d/.test(str); } console.log(startsWithNumber('avocado 123')); // 👉️ false console.log(startsWithNumber('123 avocado')); // 👉️ true console.log(startsWithNumber('0.5 test')); // 👉️ true // ✅️ Get number from start of string ✅ function getNumberAtEnd(str) { if (startsWithNumber(str)) { return Number(str.match(/^\d+/)[0]); } return null; } console.log(getNumberAtEnd('avocado 123')); // 👉️ null console.log(getNumberAtEnd('123 avocado')); // 👉️ 123 console.log(getNumberAtEnd('0.5 test')); // 👉️ 0

We used the RegExp.test method to check if a string ends with a number.

The forward slashes / / mark the beginning and end of the regular expression.

The caret ^ matches the beginning of the input.

The \d special character matches digits in the range of 0 to 9. Using the\d special character is the same as using a range like [0-9].

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

In its entirety, the regular expression matches one or more digits at the beginning of the string.

The second function we defined uses the String.match method.

Notice that we added a + at the end of the regex. The plus matches the preceding item (digits range) one or more times.

If the match method matches the regular expression in the string it returns an array containing the matches.

If no matches are found, the method returns null.

We used our startsWithNumber function to verify that there will be a match before calling the match method.

The last step is to convert the matched string to a number and return the result.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.