Check if a String ends with a Number in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

banner

Photo by Tamara Bellis

Check if a String ends with a Number #

To check if a string ends with a number, call the test() method on a regular expression that matches one or more numbers at the end a string. The test method returns true if the regular expression is matched in the string and false otherwise.

index.js
// โœ… Check if Strings ends with Number โœ… function endsWithNumber(str) { return /[0-9]+$/.test(str); } console.log(endsWithNumber('hello 123')); // ๐Ÿ‘‰๏ธ true console.log(endsWithNumber('123 apple')); // ๐Ÿ‘‰๏ธ false console.log(endsWithNumber('test 0.5')); // ๐Ÿ‘‰๏ธ true // โœ… Get number at end of string โœ… function getNumberAtEnd(str) { if (endsWithNumber(str)) { return Number(str.match(/[0-9]+$/)[0]); } return null; } console.log(getNumberAtEnd('hello 123')); // ๐Ÿ‘‰๏ธ 123 console.log(getNumberAtEnd('123 apple')); // ๐Ÿ‘‰๏ธ null console.log(getNumberAtEnd('test 0.5')); // ๐Ÿ‘‰๏ธ 5

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 square brackets [] are called a character class and match any digit in the range of 0 to 9.

The plus + matches the preceding item (the range of digits) one or more times.

The dollar $ sign matches the end of the input.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.

In its entirety the regular expression matches one or more digits at the end of a string.

Our second function uses the same regular expression with the String.match method to get the number at the end of the string.

The match method returns an array containing the matches. If there are no matches it returns null.

We used the endsWithNumber function to verify that there will be a match in advance before calling the match method.

Lastly, we convert the extracted value to a number, using the Number object.

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