Javascript获取不带querystring的url

Javascript get url without querystring

本文关键字:url querystring 获取 Javascript      更新时间:2023-09-26

我有以下url:

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

如果没有querystring,我该如何获取url?好的,现在我正在做以下操作,但有没有一种方法可以做到这一点,而不是添加两个?

window.location.origin + window.location.pathname

要获得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
}

例如,location.href.split("?")[0]?分割,并取结果数组的第一个元素。即使位置上没有?,它也能工作——整个url将是数组的单个元素。

ps:downvester-评论?不要做胆小鬼。