Categories
JavaScript Answers

How to split string variable from last slash with JavaScript?

Spread the love

Sometimes, we want to split string variable from last slash with JavaScript.

In this article, we’ll look at how to split string variable from last slash with JavaScript.

How to split string variable from last slash with JavaScript?

To split string variable from last slash with JavaScript, we can use the string lastIndexOf method.

For instance, we write

const rest = str.substring(0, str.lastIndexOf("/") + 1);
const last = str.substring(str.lastIndexOf("/") + 1, str.length);

to call substring with the index of the last / with lastIndexOf.

We get the substring before the last / with str.substring(0, str.lastIndexOf("/") + 1).

And we get the substring from the last / to the end with str.substring(str.lastIndexOf("/") + 1, str.length).

Conclusion

To split string variable from last slash with JavaScript, we can use the string lastIndexOf method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *