Advertisements
I can get the last character of the last part of the URL by using the split method and pop method such as
.split("/").pop()
.
But usually, there is a slash at the end of the URL like so: https://exmaple.com/123/456/
It will return empty because there is simply nothing after the last slash.
How do I get the number ‘6’ that is in the last part of the URL in the best and easy way?
>Solution :
One option would be to just remove the slashes, and return the last character no matter what it is.
Here’s a quick example:
const getLastChar = (str) =>
str.replaceAll('/', '').slice(-1);
// Example #1 - Trailing slash
console.log(getLastChar('https://exmaple.com/123/456/'));
// Example #2 - No trailing slash
console.log(getLastChar('https://exmaple.com/123/456'));
If it’s based on user input, don’t forget to also check that the string is present / defined too 🙂