Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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: https://exmaple.com/123/456/

It will return empty because there is simply nothing after the last slash.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading