jQuery解析url

咱们能够经过window.location很简单的解析出当前url里面包含的信息,好比:html

var protocol = window.location.protocol;

可是当你只有一个字符串的url或者将其附加到任何一个DOM元素节点上,好比 a 标签,然而window.location此时并不能帮助你解析出你想要的东西。好比下面的连接,你想解析出protocol,host name,hash,query string等等,jquery

var url = “http://jquerybyexample.net/codes/code-repository?id=12#top”;

首先你可能会想到使用正则表达式,不错这是一个好方法,可是jQuery能够经过简单的代码作到这一切,代码以下:正则表达式

$(document).ready(function () {
    var url = 'http://iwjw.com/codes/code-repository?id=12#top';
    var a = $('<a>', { href: url});
    var sResult = '<b>Protocol:</b> ' + a.prop('protocol') + '<br>'     + '<b>Host name: </b>' + a.prop('hostname') + '<br>'
    + '<b>Path: </b>' + a.prop('pathname') + '<br>'
    + '<b>Query: </b>' + a.prop('search') + '<br>'
    + '<b>Hash: </b>' + a.prop('hash');
    $('span').html(sResult);
}); </a>

实例:https://jsfiddle.net/ghostcode/umr6sxjr/2/url

相关文章
相关标签/搜索