如何在javascript中获取完整网址但没有主机?

时间:2018-04-04 19:14:57

标签: javascript

如果我有这样的链接

https://example.com:3000/sub/sub?a=1#f

我怎样才能提取

/sub/sub?a=1#f

4 个答案:

答案 0 :(得分:2)

使用location.pathname + location.search + location.hash

请参阅https://developer.mozilla.org/en-US/docs/Web/API/Location

答案 1 :(得分:2)

render() {
    const { project1 } = this.state;
    return (
      <div>
        <button onClick={onClick()} />
      </div>
    )
  }

这会摘录你要求的部分。

答案 2 :(得分:2)

另一种选择是location.href.split('/').slice(3).join('/')。 由于网址始终以http://{domain}/https://{domain}/开头,因此如果您按/分割,那么您想要的是来自第3个元素的数组。

&#13;
&#13;
var getLocation = function(href) {
  return href.split('/').slice(3).join('/');
};
var l = getLocation("https://example.com:3000/sub/sub?a=1#f");

console.log(l)
&#13;
&#13;
&#13;

或者您只需使用location.pathname + location.search + location.hash

即可

答案 3 :(得分:-1)

位置全局变量的一个属性:

window.location.pathname