Check if a String ends with a Number in JavaScript


Borislav Hadzhiev

Last updated: Oct 27, 2021


Photo from Unsplash

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.

// ✅ 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 #

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.