Get the value of a String after last Slash in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 08 20212 min read

banner

Photo by Austin Ban

Get the value of a String after the last Slash #

To get the value of a string after the last slash, call the substring() method, passing it the index, after the last index of a / character as a parameter. The substring method returns a new string, containing the specified part of the original string.

index.js
const str = '/hello/world/index.html'; const afterLastSlash = str.substring(str.lastIndexOf('/') + 1); console.log(afterLastSlash); // ๐Ÿ‘‰๏ธ index.html

The parameter we passed to the String.substring method is the start index - the index of the first character to be included in the returned string.

We used the String.lastIndexOf method to get the index of the last slash character in the string.

We don't want to include the last slash in the returned string, therefore we increment the index by 1.

The substring method does not change the original string, it returns a new string containing a part of the original string. Strings are immutable in JavaScript.

Note that the lastIndexOf method returns -1 in case it doesn't find the character in the string.

An alternative, perhaps simpler approach is to use the split and pop methods.

index.js
const str = 'hello/world/index.html'; const afterLastSlash = str.split('/').pop(); console.log(afterLastSlash); // ๐Ÿ‘‰๏ธ index.html

In the code snippet, we first call the String.split method to split on a / character.

This returns an array of strings without the / separator.

index.js
const str = 'hello/world/index.html'; const splitOnSlash = str.split('/'); console.log(splitOnSlash); // ๐Ÿ‘‰๏ธ ['hello', 'world', 'index.html']

We then call the Array.pop method which removes and returns the last element of the array.

If you care about performance you would use the 1st approach, even though the difference is negligible, unless you're dealing with huge strings.

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