Get the Number from the End of a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Aziz Acharki

Get the Number from the End of a String #

To get the number from the end of a string, call the match() method, passing it the following regular expression [0-9]+$. The match method will return an array containing the number from the end of the string at index 0.

index.js
const str = 'one 2 three 456'; const arr = str.match(/[0-9]+$/); console.log(arr); // ๐Ÿ‘‰๏ธ ['456'] const num = parseInt(arr[0], 10); console.log(num); // ๐Ÿ‘‰๏ธ 456

We used the String.match method to get an array containing the number at the end of a string.

The only parameter the method takes is a regular expression.

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

The square brackets [] part is called a character class and matches a range of digits from 0 to 9.

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

The dollar sign $ matches the end of the input.

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

Once we have the array containing the digits match, we use the parseInt function to parse the string into a number.

If the regular expression is not matched in the string (the string contains no digits at the end), the match method will return null.
index.js
const str = 'one 2 three 456 seven'; const arr = str.match(/[0-9]+$/); console.log(arr); // ๐Ÿ‘‰๏ธ null

If you need to handle this scenario, you can use an if statement.

index.js
const str = 'one 2 three 456 seven'; const arr = str.match(/[0-9]+$/); console.log(arr); // ๐Ÿ‘‰๏ธ null let num; if (arr !== null) { console.log('โœ… String contains digits at the end'); num = parseInt(arr[0], 10); } else { console.log('โ›”๏ธ String contains NO digits at the end'); }

In this example, we only call the parseInt function, if we are sure the string contains digits at the end.

Trying to access the element at index 0 on a null value would give us an error, so it's good to handle these scenarios.

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