Detailed explanation of the URL Parsing Method in Javascript, and url parsing in javascript
URL: Uniform Resource Locator (Uniform Resource Locator, URL)
The complete URL consists of the following parts:
Scheme: // host: port/path? Query # fragment
Scheme = communication protocol (Common http, ftp, maito, etc)
Host = host (domain name or IP address)
Port = port number
Path = path
Query = query
Optional. Used for dynamic web pages (such as CGI, ISAPI, PHP/JSP/ASP. NET and other technologies) Transfer Parameters. Multiple parameters can be separated by the "&" symbol. The names and values of each parameter are separated by the "=" symbol.
Fragment = Information fragment
String used to specify fragments in network resources. For example, if a webpage contains multiple glossary, you can use fragment to directly locate the glossary. (Also called anchor .)
For such a URL
Http://www.master8.net: 80/seo /? Ver = 1.0 & id = 6 # imhere
We can use javascript to obtain all the parts.
1, window. location. href
The whole URl string (the complete address bar in the browser)
2, window. location. protocol
URL protocol section
Returned value in this example: http:
3, window. location. host
Host part of the URL
Returned value in this example: www.master8.net
4, window. location. port
URL Port
If the default port 80 is used (update: Even if port 80 is added), the return value is not the default port 80, but an empty character.
Returned value in this example :""
5, window. location. pathname
URL path (that is, the file address)
Returned value in this example:/seo/
6. window. location. search
Query (parameter)
In addition to assigning values to dynamic languages, we can also assign values to static pages and use javascript to obtain expected parameter values.
Return Value in this example :? Ver = 1.0 & id = 6
7. window. location. hash
Anchor
Returned value in this example: # imhere
8. url parameter value
Method 1: Regular Expression Analysis
Copy codeThe Code is as follows:
Function getQueryString (name ){
Var reg = new RegExp ("(^ | &)" + name + "= ([^ &] *) (& | $)", "I ");
Var r = window. location. search. substr (1). match (reg );
If (r! = Null) return unescape (r [2]); return null;
}
Method 2: split an array using split
Copy codeThe Code is as follows:
Function GetRequest (){
Var url = location. search; // get the url "? "Character String
Var theRequest = new Object ();
If (url. indexOf ("? ")! =-1 ){
Var str = url. substr (1 );
Strs = str. split ("&");
For (var I = 0; I <strs. length; I ++ ){
TheRequest [strs [I]. split ("=") [0] = unescape (strs [I]. split ("=") [1]);
}
}
Return theRequest;
}
The method is very simple, but it is very practical. Two methods are listed here. Please let me know if you have different methods. This article will be updated continuously. Common progress