"JavaScript" gets the URL of the current page with the Window.location.href

Source: Internet
Author: User

Using JavaScript to get the URL of the current page is a complicated question, and if you think about it for the first time, many people are wondering what kind of javascript function it is.

Actually, the function that JavaScript gets the URL of the current page is the window.location.href that we often use to redirect.

For example, the following function:

<script>var Url=window.location.href;var loc = url.substring (Url.lastindexof ('/') +1, url.length); Alert ("Url=" +url+ ", loc=" +loc);</script>

If the URL of the current page is http://localhost:6666/myphp/mobile/pc1.php, then it runs as follows:


The above function shows how to get the current page name.

After obtaining the entire URL using the variable of window.location.href, which part of the address to use, using string processing functions such as substring,indexof to handle the obtained URL, intercept the part you want.

Usually use Window.location.href to redirect, is to change the URL of the entire browser,

If there is no assignment later, this becomes the statement that gets the current value.

As with document.getElementById ("XX"). Value, you can modify it to get it.

Of course, if you get some specific value, such as the current protocol and port, you don't have to intercept the string.

Directly using the Window.location.port port, Window.location.protocol get the protocol, Window.location.search can also take the part of the URL question mark, of course, you can also use them to change the corresponding value.

For example, the following code:

Alert ("Protocol:" +window.location.protocol+ ", Port:" +window.location.port);
The results of the operation are as follows:


"JavaScript" gets the URL of the current page with the Window.location.href

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.