最简单的URL解析方法

2017-01-24  本文已影响0人  大前端之路
function parseURL(url) {
  var parser = document.createElement("a"),
      searchObj = {},
      queries,key, value

  parser.href = url
  queries = parser.search.replace(/^\?/, "").split("&")
  queries.forEach((query) => {
    key = query.split("=")[0]
    value = query.split("=")[1]
    searchObj[key] = value
  })

  return {
    protocol: parser.protocol,
    host: parser.host,
    hostname: parser.hostname,
    port: parser.port,
    pathname: parser.pathname,
    searchObj: searchObj,
    hash: parser.hash
  }
}
new URL('https://gist.github.com/jlong/2428561?foo=bar#test') =>
    {
        hash: "#test",
        search: "?foo=bar",
        pathname: "/jlong/2428561",
        port: "",
        hostname: "gist.github.com",
        host: "gist.github.com",
        password: "",
        username: "",
        protocol: "https:",
        origin: "https://gist.github.com",
        href: "https://gist.github.com/jlong/2428561?foo=bar#test"
    }
    var parser = document.createElement('a');
    parser.href = "http://example.com:3000/pathname/?search=1&a=2#hash";

    parser.protocol; // => "http:"
    parser.hostname; // => "example.com"
    parser.port;     // => "3000"
    parser.pathname; // => "/pathname/"
    parser.search;   // => "?search=test"
    parser.hash;     // => "#hash"
    parser.host;     // => "example.com:3000"

    console.log(parser.search);
上一篇下一篇

猜你喜欢

热点阅读