Created
September 7, 2013 15:13
-
-
Save RockyMyx/6476456 to your computer and use it in GitHub Desktop.
JavaScript: parse-url.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//http://tutorialzine.com/2013/07/quick-tip-parse-urls/ | |
$(function(){ | |
// The URL we want to parse | |
var url = 'http://tutorialzine.com/2013/07/quick-tip-parse-urls/?key=value#comments'; | |
// The magic: create a new anchor element, and set the URL as its href attribute. | |
// Notice that I am accessing the DOM element inside the jQuery object with [0]: | |
var a = $('<a>', { href:url } )[0]; | |
$('#host').val(a.hostname); | |
$('#path').val(a.pathname); | |
$('#query').val(a.search); | |
$('#hash').val(a.hash); | |
// Even more: | |
// a.port, a.protocol, | |
// a.origin (not available in older IE versions) | |
}); | |
$(function(){ | |
// Get only the external links: | |
var external = $('a[href]').filter(function(){ | |
return this.hostname != location.hostname; | |
}); | |
// In the return above, you may also compare the protocol | |
// property if you wish to distinguish http from https links. | |
external.addClass('external'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment