Get URL Path without last segment
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)
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