Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 452
albuvee Avatar asked Dec 12 '12 17:12

albuvee


2 Answers

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)
like image 144
mplungjan Avatar answered Sep 17 '22 13:09

mplungjan


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

like image 25
KingKongFrog Avatar answered Sep 17 '22 13:09

KingKongFrog