[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: