samuel toh samuel toh - 9 months ago 28
jQuery Question

How to remove the last two parts from a URL?

I have the following URL: http://myshop.dev/member/message/inbox/detail/58c4fad6607a1d16f0006b3b

I want to remove the last two parts, so this would produce: http://myshop.dev/member/message/inbox

I tried like this :

var vars = "http://myshop.dev/member/message/inbox/detail/58c4fad6607a1d16f0006b3b";
var arrVars = vars.split("/");
var lastVar = arrVars.pop();
var restVar = arrVars.join("/");
console.log(restVar);


It only successfully removes the last part.

I want to remove one more part.

How can I do that?

Answer Source

Just pop it again. :)

var vars = "http://myshop.dev/member/message/inbox/detail/58c4fad6607a1d16f0006b3b";
var arrVars = vars.split("/");
arrVars.pop();
arrVars.pop();
var restVar = arrVars.join("/");
console.log(restVar);

Or you could just use splice:

var vars = "http://myshop.dev/member/message/inbox/detail/58c4fad6607a1d16f0006b3b";
var arrVars = vars.split("/");
arrVars.splice(-1,2)
var restVar = arrVars.join("/");
console.log(restVar);