Split variable from last slash

var txt = "var1/var2/var3";
txt = txt.split('/')

var Var1 = txt.pop();
var Var2 = txt[0]+'/'+txt[1];

alert(Var1);
alert(Var2);

var last  = url.split("/").pop();
console.log(last);

You can get last piece of url with array pop method.


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);

Try something like this:

var vars = "var1/var2/var3";
var arrVars = vars.split("/");
var lastVar = arrVars.pop();
var restVar = arrVars.join("/");
alert(lastVar);
alert(restVar);

Tags:

Javascript