您的位置:首页 > Web前端 > JavaScript

[JavaScript]How to parse the URL and get the different fragments easily?

2014-01-19 08:19 686 查看
In this tutorial, i will show you how to get the href, protocol,host, host name,port and path information from URL with the help of JS.

var urlParsingNode = document.createElement("a");
var originUrl = urlResolve(window.location.href, true);

function urlResolve(url, base) {
var href = url;

if (msie) {
// Normalize before parse.  Refer Implementation Notes on why this is
// done in two steps on IE.
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}

urlParsingNode.setAttribute('href', href);

return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/')
? urlParsingNode.pathname
: '/' + urlParsingNode.pathname
};
}

function urlIsSameOrigin(requestUrl) {
var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
return (parsed.protocol === originUrl.protocol &&
parsed.host === originUrl.host);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: