Js: Simple Method for getting 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:
Supplement: substring (start, stop) Knowledge
Syntax
Syntax stringObject. substring (start, stop)
Return Value
A new string that containsStringObjectThe content of a substring is fromStartToStop-All characters at 1. The length isStopSubtractionStart.
Description
The substring returned by the substring () method includesStartBut does not includeStop.
If the ParameterStartAndStopEquals, then this method returns an empty string (that is, a string with a length of 0 ). IfStartRatioStopThis method swaps the two parameters before extracting the substring.
The simple method of getting the URL and window. location. href of the current page from this js file is to share all the content with you. I hope to give you a reference and support for the customer's house.