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

0 Response to "URL Parser"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel