[JavaScript]How to parse the URL and get the different fragments easily?
时间:2014-01-20 22:47:55
收藏:0
阅读:419
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); }
原文:http://blog.csdn.net/wonderfan/article/details/18495323
评论(0)