Filter last slash of URL and return the last character


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:

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

// Example #2 - No trailing slash

If it’s based on user input, don’t forget to also check that the string is present / defined too 🙂

Leave a ReplyCancel reply