Borislav Hadzhiev
Tue Oct 26 2021·2 min read
Photo by Aziz Acharki
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
.
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
.
+
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.
match
method will return null
.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.
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.