[JavaScript] obtain the URL of the current page and window. location. href, window. location. href

Source: Internet
Author: User

[JavaScript] obtain the URL of the current page and window. location. href, window. location. href

Using Javascript to get the URL of the current page seems complicated. If you think about the problem for the first time, many people may wonder which Javascript function is actually used.

Actually, no. The function of Javascript to get the URL of the current page is the window. location. href that we often use to redirect.

For example:

<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, the running result is as follows:


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

Obtain the window. location. after the href variable obtains the whole url, it uses the string processing functions such as substring and indexof to process the obtained url and intercept the desired part.

Usually, window. location. href is used for redirection to change the url of the entire browser,

If no value is assigned, this is the statement for obtaining the current value.

Like document. getElementById ("xx"). value, you can modify it to obtain it.

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

Directly use window. location. port: port used, window. location. protocol, window. location. search can also take the part after the url question mark, and can also use them to change the corresponding value.

For example, the following code:

alert("protocol:"+window.location.protocol+",port:"+window.location.port);
The running result is as follows:


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.