albuvee
albuvee

Reputation: 2764

Get URL Path without last segment

How can I get the URL Path of the current site, but without the last segment:

http://www.domain.com/first/second/last

I only need http://www.domain.com/first/second … with jQuery (or only JavaScript)

Upvotes: 15

Views: 23036

Answers (4)

mplungjan
mplungjan

Reputation: 178413

Using pop and URL api

this assumes the URL is not likely to change

I use document.URL since that is what is recommended

const url = new URL("https://www.example.com/first/second/last"); // new URL(document.URL)
let path = url.pathname.split("/");
path.pop(); // remove the last
url.pathname = path.join("/")
console.log(url)

Older answers: As requested by OP - with changes from comment

const url = "http://www.example.com/first/second/last", // document.URL, 
    shortUrl=url.substring(0,url.lastIndexOf("/"));
console.log(shortUrl)    

Here is an alternative

const url = new URL("http://www.example.com/first/second/last"),
      shortUrl = `${url.protocol}//${url.hostname}${url.pathname.slice(0,url.pathname.lastIndexOf("/"))}`

console.log(shortUrl)

Upvotes: 21

Emily
Emily

Reputation: 6069

I'm not sure this is the most elegant of solutions, but you just want the substring up to the last slash, or second to last if the last character is a slash. Here I first take the part of the URL that appears after the protocol (http:// or https://) so that on for example http://stackoverflow.com it returns http://stackoverflow.com.

    var url = document.URL.split('://');
    var last_slash;
    var result;
    if (url[1].charAt(url[1].length - 1) === '/') {
      url[1] = url[1].substring(0, url[1].length - 1);
    }
    last_slash = url[1].lastIndexOf('/');
    result = url[0] + '://' + ((last_slash !== -1) ? url[1].substring(0, last_slash) : url[1]);

edit: jsfiddle http://jsfiddle.net/CV6d4/

Upvotes: 0

KingKongFrog
KingKongFrog

Reputation: 14429

http://jsfiddle.net/KZsEW

Try the following for all browsers:

var url = "http://www.domain.com/first/second/last";  // or var url = document.URL;
var subUrl = url.substring(0,url.lastIndexOf("/"))

alert(subUrl);
​

The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

Note: The string is searched from the end to the beginning, but returns the index starting at the beginning, at postion 0.

This method returns -1 if the value to search for never occurs.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf

Upvotes: 8

A. Magalhães
A. Magalhães

Reputation: 1516

Try this:

var url = 'http://www.domain.com/first/second/last';
for(var i=url.length-1; i>=0;i--){
    if(url[i]!='/'){
        url= url.substr(0,i);
    }
    else{
        alert(url);
        break;
    }
}

Upvotes: 0

Related Questions