Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split variable from last slash

Tags:

javascript

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?

like image 833
Alfred Avatar asked Apr 05 '11 16:04

Alfred


People also ask

How do you get the string after the last slash?

First, find the last index of ('/') using . lastIndexOf(str) method. Use the . substring() method to get the access the string after last slash.

How do you get the last split element?

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.

How do you split a URL?

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.


1 Answers

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);
like image 132
Mark Coleman Avatar answered Oct 14 '22 17:10

Mark Coleman