https://cdn.statically.io/gh/dte-project/a/1e23173799f8ac7c346f345f20de4e5ccb246b1e/shell.v2.min.css
Loading...

Minggu, 24 Februari 2013

// 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

View more articles

Keyword link

Subscribe via Email

Sign up by email to get the latest news from us..

Contact us

Send a message to us.

Template Hasil Cloning II | Copyright 2015 - 2016 | Rip Code by Shn | ShannenPio Cloning