[JavaScript] How to parse the URL and get the different fragm

Source: Internet
Author: User

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);}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.