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?

Answers 1

  • Instead of calling pop() twice you can use splice() or slice() like this:

    splice() - w3schools docs

    var vars = "http://myshop.dev/member/message/inbox/detail/58c4fad6607a1d16f0006b3b";
    var arrVars = vars.split("/");
    
    // remove desired # of URL pieces here in 2nd parameter:
    arrVars.splice(-2, 2);
    var restVar = arrVars.join("/");
    

    slice() - w3schools docs

    var vars = "http://myshop.dev/member/message/inbox/detail/58c4fad6607a1d16f0006b3b";
    var arrVars = vars.split("/");
    var arrLength = arrVars.length;
    
    // remove desired # of URL pieces here:
    var arrVars = arrVars.slice(0, arrLength - 2);
    var restVar = arrVars.join("/");
    

Related Articles