Check if String starts with Number using JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

banner

Photo by Jens Kreuter

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.

index.js
// โœ… 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee