Common ways for JavaScript to get URL information

Source: Internet
Author: User

Take "http://www.cnblogs.com/wuxibolgs329/p/6188619.html#flag?test=12345" as an example, and then get the various components of it.

1 . Get the full URL of the page

var a=location.href; Console.log (a); //"http://www.cnblogs.com/wuxibolgs329/p/5261577.html#flag?test=12345"

2. Get the domain name of the page

var host = Window.location.host; //www.cnblogs.com

var host2 = document.domain; //www.cnblogs.com

var a = Location.hostname; //www.cnblogs.com

3. get the URL agreement

var a=location.protocol;console.log (a); //http:

4. Get the Port

var a=location.port;console.log (a);

5. get the page path

var a=location.pathname;console.log (a);

6. set or get the protocol portion of the URL

var a = Location.protocol;

7 . Get the part after #

var A=window.location.hash; var b=a.substr (1); Console.log (b); //flag?test=12345

8. get the href attribute with the question mark in the following section

At this point the case address changes to "http://www.cnblogs.com/wuxibolgs329/p/5261577.html? test=12345". Get test=12345

var A=location.search;
var b=a.substr (1);
Console.log (b);

If the case is still "http://www.cnblogs.com/wuxibolgs329/p/5261577.html#flag?test=12345", the following wording is required to get test=12345
var a=location.href;
var b=a.substr (A.lastindexof ('? ') +1);
Console.log (b);

9. Get the part after the = sign

var A=location.href;var b=a.substring (a.lastindexof (' = ') +1); Console.log (b); 12345

Common ways for JavaScript to get URL information

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.