Sunday, February 24, 2013

URL Parser

// This function creates a new anchor element and uses location
// properties (inherent) to get the desired URL data. Some String
// operations are used (to normalize results across browsers).
// Read => http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

function parseURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':', ''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function() {
            var ret = {},
            seg = a.search.replace(/^\?/, '').split('&'),
                len = seg.length,
                i = 0, s;
            for (; i < len; i++) {
                if (!seg[i]) {
                    continue;
                }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        path: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/')
    };
}

Penggunaan

Data yang diparse nantinya akan berubah menjadi objek seperti ini:

{
    source: "XXX",
    protocol: "XXX",
    host: "XXX",
    port: "XXX",
    query: "XXX",
    params: {
        "XXX": "XXX",
        "XXX": "XXX",
        "XXX": "XXX",
        "XXX": "XXX"
    },
    file: "XXX",
    hash: "XXX",
    path: "XXX",
    relative: "XXX",
    segments: ["XXX", "XXX", "XXX"]
}

Dari situ kita bisa memanggil setiap bagian dari objek yang dihasilkan dengan cara yang sama seperti saat kita memanggil data pada objek. Misalnya:

var myUrl = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');

alert(myUrl.protocol); // => akan menghasilkan `http`

Selengkapnya

myUrl.file;     // = 'index.html'
myUrl.hash;     // = 'top'
myUrl.host;     // = 'abc.com'
myUrl.query;    // = '?id=255&m=hello'
myUrl.params;   // = Object = { id: 255, m: hello }
myUrl.path;     // = '/dir/index.html'
myUrl.segments; // = Array = ['dir', 'index.html']
myUrl.port;     // = '8080'
myUrl.protocol; // = 'http'
myUrl.source;   // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'

Lihat Demo


Sumber: James Padolsey – Parsing URLs with the DOM!

Lainnya

Labels: , ,

2 Comments:

At Sunday, April 14, 2013 at 7:14:00 PM GMT+7, Blogger budkalon said...

URL Pareser itu untuk apa fungsinya? :Ozz

 
At Friday, September 27, 2013 at 12:58:00 PM GMT+7, Blogger ahmad najiullah said...

klo dirubah jadi automatis ketika halaman diload bagaimana om?

 

Post a Comment

<< Home