jQuery解析url

Zhuxy發表於2015-08-24

我們可以通過window.location很簡單的解析出當前url裡面包含的資訊,比如:

var protocol = window.location.protocol;

但是當你只有一個字串的url或者將其附加到任何一個DOM元素節點上,比如 a 標籤,然而window.location此時並不能幫助你解析出你想要的東西。比如下面的連結,你想解析出protocol,host name,hash,query string等等,

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/

相關文章