JavaScript获取不带查询字符串的URL

3

I have the following url:

url = 'http://stackoverflow.com/questions/ask?new=question'

我该如何获取不带查询字符串的URL?目前,我正在执行以下操作,但是否有一种单一的方法可以代替添加两个方法来实现此功能?

window.location.origin + window.location.pathname
2个回答

6
为了获取URL的所有不同部分,正确的语法是location.protocol + '//' + location.host + location.pathname。以下示例显示了此片段所托管的URL:

document.body.innerHTML = "The snippet is at this web address: " + getURL();

function getURL() {
  return location.protocol + '//' + location.host + location.pathname
}


5
例如像这样 - location.href.split("?")[0] - 通过?拆分数组并取其第一个元素。即使在位置中没有?,整个URL也将是数组的单个元素。
注:下投票者 - 有评论吗?不要胆小。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接