Javascript parsing URL method

  • 2020-03-30 04:29:47
  • OfStack

URL: Uniform Resource Locator (URL)

The complete URL consists of these parts:
Scheme: / / host: port/path & # 63; Query# fragments

Scheme  = communication protocol (commonly used HTTP, FTP,maito, etc.)
Host = host (domain name or IP)
Port = port number
Path = path

Query = query
Optional, used to pass parameters to dynamic web pages (such as web pages made using CGI, ISAPI, PHP/JSP/ASP/ASP.NET, etc.), can have multiple parameters separated by the "&" symbol, and the name and value of each parameter separated by the "=" symbol.

Fragment = fragment of information
A string that specifies a fragment in a network resource. For example, a web page with more than one noun explanation, you can use fragment to directly locate a noun explanation. (also known as anchor points.)

For a URL like this
(link: http://www.master8.net:80/seo/? Ver = 1.0 & id = 6 # imhere)

We can use javascript to get the various parts of it
1, the window. The location. The href
The entire URl string (which in the browser is the entire address bar)

2, the window. The location. The protocol
The protocol part of the URL
Return value: HTTP:

3, the window. The location. The host
The host part of the URL
Return value of this example :www.master8.net

4, the window. The location. The port
The port part of the URL
If the default port 80 is used (update: even if :80 is added), the return value is not the default 80 but a null character
Return value of this example: ""

5, the window. The location. The pathname
The path part of the URL (that is, the file address)
Return value :/seo/

6, the window. The location. The search
Query (parameter) section
In addition to assigning values to dynamic languages, we can also assign static pages and use javascript to get the values of the parameters we believe to be appropriate
Return value :? Ver = 1.0 & id = 6

7, the window. The location. The hash
The anchor
This example returns a value :#imhere

8. Url parameter value

Method 1: regular analysis


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 into arrays


function GetRequest() {
   var url = location.search; //Get "?" in the url 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, here is a list of two of their common methods, friends have different methods please let me know, this article is constantly updated. Make progress together


Related articles: