I have a variable var1/var2/var3
. I want to store var3
the part after last slash in a variable and the part before that (var1/var2/
) in another variable. How can I do this?
First, find the last index of ('/') using . lastIndexOf(str) method. Use the . substring() method to get the access the string after last slash.
To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.
To split the URL to get URL path in with JavaScript, we can create a URL instance from the URL string. Then we can use the pathname property to get the URL path. For instance, we write: const url = 'http://www.example.com/foo/path2/path3/path4'; const { pathname } = new URL(url); console.
You can use lastIndexOf
to get the last variable and that to get the rest.
var rest = str.substring(0, str.lastIndexOf("/") + 1); var last = str.substring(str.lastIndexOf("/") + 1, str.length);
Example on jsfiddle.
var str = "var1/var2/var3"; var rest = str.substring(0, str.lastIndexOf("/") + 1); var last = str.substring(str.lastIndexOf("/") + 1, str.length); console.log(rest); console.log(last);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With