URL JavaScript Solution

Source: Internet
Author: User

In most cases, URLs are a concern of backend programmers, but sometimes they also need to deal with them, one thing that many people may have done is to jump to the page by writing the href attribute, but this is not all the topic to be discussed today. For URLs, we need to know more, because we may need to extract some URL information for different purposes during development. In fact, this is also a unique way to interact with the backend, of course, this is safe. When a request is returned, URL information is recorded in the location attribute of the window object, the result of the value does not change as the user manually modifies the characters in the address bar. This is very important. After learning about the content, let's start with the figure below:

Don't be confused by the color blocks. The long string in the middle of the picture is a complete URL, which contains any part of a URL: protocol, domain name, port number, path, parameter, and description. In JavaScript, the method to obtain this line of string is to access window. Location. href. The href attribute contains a complete URL of the page. If you want to get the value of a part of the URL, we can use a complex and cumbersome regular expression to parse the complete URL, but the more convenient way is to obtain it through other properties of location. For example, the Protocol attribute of location records the protocol name with a colon, and the pathname attribute stores the path name. These attributes are separated by href, which makes it easier for developers. The following table lists all the properties in location and their respective recorded values. If you cannot understand the content in the table, the color block and text in the figure above describe the location of each attribute in the URL.

Attribute Value
Href Complete URL
Protocol Protocol
Hostname Host Name
Host Host name and port number
Port Port Number
Pathname Path section of the current URL
Search URL Query
Hash # Start anchor

It is worth noting that the above attributes are writable, which means we can change their values through JavaScript. Most of these attributes are simple at a Glance. Only the search part is troublesome, And the search part is transmitted to the backend parameters in get mode? Start, & as the separator, = The serialized string of the value assignment, so that the location. the value obtained by search is often not the final result. We can analyze the result by using the search structure. We may want to get an associated array containing clear mappings. So we need to further process the string obtained in location. Search.

function getArgs() {    var args = {};    var query = location.search.substring(1);     // Get query string    var pairs = query.split("&");                 // Break at ampersand    for(var i = 0; i < pairs.length; i++) {        var pos = pairs[i].indexOf('=');          // Look for "name=value"        if (pos == -1) continue;                  // If not found, skip        var argname = pairs[i].substring(0,pos);  // Extract the name        var value = pairs[i].substring(pos+1);    // Extract the value        value = decodeURIComponent(value);        // Decode it, if needed        args[argname] = value;                    // Store as a property    }    return args;                                  // Return the object}

The above Code comes from the Javascript authoritative guide. The getargs method does not receive parameters. It actively extracts the search part of the URL for parsing and returns a JSON value. For example, if we use the getargs method to get the URL in the first image, we will get the following result:

var search = {    "q" : "123",    "a" : "321"}

In this way, all URL Information can get a very clear result, which is very simple. However, we recommend the doomain method. The method uses regular expressions to parse URLs for the same purpose, but the running efficiency is higher and the code is more concise. The code for this method is on the 13th floor of this Article. Click here to arrive quickly.

Related Article

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.