Fri Oct 08 2021·2 min read
Photo by Austin Ban
To get the value of a string after the last slash, call the
method, passing it the index, after the last index of a
/ character as a
substring method returns a new string, containing the specified
part of the original string.
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
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
const str = 'hello/world/index.html'; const afterLastSlash = str.split('/').pop(); console.log(afterLastSlash); // 👉️ index.html
In the code snippet, we first call the
method to split on a
This returns an array of strings without the
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.
I'll send you 1 email a week with links to all of the articles I've written that week