Thursday, May 22, 2014

Getting parts of a URL without using regex

As this response on StackOverflow says, have the browser do it for you:

var a = document.createElement('a');
a.href = 'http://www.example.com:123/foo/bar.html?fox=trot#foo';

['href','protocol','host','hostname','port','pathname','search','hash'].forEach(function(k) {
    console.log(k+':', a[k]);
});

/*//Output:
href: http://www.example.com:123/foo/bar.html?fox=trot#foo
protocol: http:
host: www.example.com:123
hostname: www.example.com
port: 123
pathname: /foo/bar.html
search: ?fox=trot
hash: #foo
*/

Or, with jQuery:

var lnk = $('<a href="http://www.example.com:123/foo/bar.html?fox=trot#foo" />')[0];
$.each(['href','protocol','host','hostname','port','pathname','search','hash'], function(idx, k) { 
  console.log(k+':', lnk[k]); 
});

No comments:

Post a Comment