给定一个有效的href,原点、路径名、搜索和散列的正则表达式是什么?

given a valid href, what are regx for origin, pathname, search and hash?

本文关键字:搜索 路径名 是什么 正则表达式 原点 href 有效 一个      更新时间:2023-09-26

javascript中,给定一个有效的url,例如,

http://seeplai2.trailsandtribulations.nat/admin/items?var=val#here

window.location中找到的提取原点、路径名、搜索和散列的表达式是什么?

regx中相对较弱,以下是我的猜测:

origin: href.match(/(.*?)('/|'?|#))[1]
pathname: href.match('/'/[^'/]*([^'?#]*)/)[1]
search: (href.indexOf('?')>-1) ? href.match(/'?[^#]*)/)[1] : ''
hash: (href.indexOf('#')>-1) ? href.match(/(#.*)/)[1] : ''

这些看起来对吗?

下面是示例代码:

<a href='/path?var=val1' onclick='doClick(event)'>Anchor1</a>
function doClick(e) {
  var href = e.target.href;
  var origin = href.match(/regx/)[1];
  // if different origin, go there
  if( origin != window.location.origin ) return;
  // if only hash difference, let default take over
  ...
  // if path different, process here
  ...
}

为什么使用regexp?

var link = document.createElement("a")
link.setAttribute("href","http://seeplai2.trailsandtribulations.nat/admin/items?var=val#here");
alert(link.search)

比较原点,使用更兼容的

location.protocol + "//" + location.hostname
例如

window.onload=function() {
  var winOrigin = location.protocol+"//"+location.hostname;
  var links = document.links;
  for (var i=0,n=links.length;i<n;i++) {
    links[i].onclick=function() {
      var linkOrigin = this.protocol + "//" + this.hostname;
      alert(winOrigin===linkOrigin);
    }
  }
}
演示;