How to use location object to parse URL without re

2019-04-13 00:25发布

问题:

The browser has a very efficient URL parser that let you get location.href, hash, query, etc from the current URL. I'd like to use it instead of coding something using regexes.

If you set location.href or do location.replace(url), the page gets redirected in Chrome. I tried to get the prototype of location in this browser, but I can't find location.prototype. There is a location.__proto__ which is described as the Location class in the js console, but I can't find a way to instantiate it. Plus, I need a cross browser solution and __proto__ is not available in IE.

If it's not possible, don't give me a regex alternative, just tell me the hard truth, provided you can back it up with evidences.

回答1:

Yes, it's very much possible! If you create a new a object, you can use the location fields without redirecting the browser.

For instance:

var a = document.createElement('a');
a.href = "http://openid.neosmart.net/mqudsi#fake"

You can now access .hash, .pathname, .host, and all the other location goodies!

> console.log(a.host);
openid.neosmart.net


回答2:

I wrote a generalized version of the wonderful Mahmoud solution:

  var parseUrl = (function(){

    var div = document.createElement('div');
    div.innerHTML = "<a></a>";

    return function(url){
      div.firstChild.href = url;
      div.innerHTML = div.innerHTML;
      return div.firstChild;
    };

  })();

It works that way:

var url = parseUrl('http://google.com');
var url = zerobin.parseUrl('http://google.com');
console.log(url.protocol);
"http:"
console.log(url.host);
"google.com"

The parseUrl code is a bit complicated because IE requires the link HTML code to be processed by its HTML parser if you want it to parse the URL. So we create a closure in which we store a <div> with a <a> as child (avoid recreating it a each call), and when we need URL parsing, we just take the HTML of div, and inject it back to itself, forcing IE to parse it.