JavaScript中解析URL

通过正则表达式来处理URL

function parseUrl(href)
{
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/),
query = null,
keyValue,
tplValue,
defaultPort =
{
"http:" : 80,
"https:" : 443,
"ftp:" : 21,
"gopher:" : 70,
"ws:" : 80,
"wws" : 443
}; ;
if (match[6])
{
keyValue = match[6].replace(/^\?/, "").split('&');
query = {};
for (var i = 0, j = keyValue.length; i < j; i++)
{
tplValue = keyValue[i].split('=');
query[tplValue[0]] = tplValue[1];
}
}
return match &&
{
href : href,
protocol : match[1],
host : match[2],
hostname : match[3],
port : match[4] || defaultPort[match[1]] || "",
path : match[5] + match[6],
pathname : match[5],
search : match[6],
hash : match[7],
query : query
}
}

发表评论

发表评论

*

沙发空缺中,还不快抢~