如何获取当前网站的URL路径,但不包括最后一段:
http://www.domain.com/first/second/last
我只需要使用jQuery(或仅JavaScript)获取http://www.domain.com/first/second
...
如何获取当前网站的URL路径,但不包括最后一段:
http://www.domain.com/first/second/last
我只需要使用jQuery(或仅JavaScript)获取http://www.domain.com/first/second
...
使用pop和URL API
假设URL不太可能改变
我使用document.URL,因为这是推荐的方法。
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)
旧回答:按照OP的要求-带有评论中的更改
const url = "http://www.example.com/first/second/last", // document.URL,
shortUrl=url.substring(0,url.lastIndexOf("/"));
console.log(shortUrl)
这里有一个替代方案
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)
var url = document.location.href, shortURL = url.substring(0,url.lastIndexOf("/"));
- albuveevar url = "http://www.domain.com/first/second/last"; // or var url = document.URL;
var subUrl = url.substring(0,url.lastIndexOf("/"))
alert(subUrl);
lastIndexOf()
方法返回一个字符串中指定值最后出现的位置。我不确定这是最优雅的解决方案,但你只需要子字符串到最后一个斜杠,如果最后一个字符是斜杠,则为倒数第二个。在这里,我首先获取出现在协议(http://或https://)之后的URL部分,以便例如http://stackoverflow.com返回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]);
编辑:jsfiddle http://jsfiddle.net/CV6d4/
试试这个:
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;
}
}
var firstpart = url.substring(0,url.lastIndexOf("/"))
- mplungjan