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'

Lainnya

Jika Anda menyukai Artikel di blog ini, Silahkan klik disini untuk berlangganan gratis via email, dengan begitu Anda akan mendapat kiriman artikel setiap ada artikel yang terbit di Creating Website

0 comments:

Post a Comment

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Homtimpa - All Rights Reserved
Template Modify by Creating Website
Proudly powered by Blogger