How to extract parameters from a URL and convert objects to URL query parameters? javascript tips-js tutorial

Source: Internet
Author: User
These two methods are mainly used to supplement the toQueryParams and Object toQueryString methods in the Sring section previously skipped in Prototype analysis. 1. Extract parameters from the URL.

Has the following strings:

Var linkURL = 'HTTP: // localhost: 8080/String/string_6.html? Nickname = xiaoxi mountain & age = 24 # id1 ';
For a real URL address, you can use js to read relevant information in location to obtain some information. The following lists some information:

The Code is as follows:


Location. origin: http: // localhost [domain]
Location. pathname:/project_js/Javascript/js_basic/demo/String/string_6.html [URL path]
Location. host: localhost [host + port]
Location. hostname: localhost [host name]
Location. port: [port]
Location. search :? Name = xesam [query string]
Location. hash: # age [anchor]
Location. href: http: // localhost/project_js/Javascript/js_basic/demo/String/string_6.html? Name = xesam # age [complete form]
Location. protocol: http [protocol]


Location. search is used to extract parameters from URLs. However, for general purpose, we do not read location. search and directly process strings.

After the string is extracted and queried, it is converted into an object.

First, we will discuss several query strings:

(1 )? Nickname = xiaoxi shanzi & age = 24 # id1 --> {nickname: 'xiaoxi shanzi ', age: '24 '}

(2 )? Nickname & age = 24 # id1'; --> {nickname: undefined, age: '24 '}

(3 )? = Hillstone & age = 24 # id1 --> {age: '24 '}

(4 )? Nickname = xiaoxi mountain son = another & age = 24 & age = 24 # id1 --> {nickname: 'xiaoxi mountain son = another ', age: ['24 ', '24']}

The Code is as follows:


Function toQueryParams (){
Var search = this. replace (/^ \ s +/, ''). replace (/\ s + $/,''). match (/([^? #] *) (#. *)? $/); // Extract '? '
If (! Search ){
Return {};
}
Var searchStr = search [1];
Var searchHash = searchStr. split ('&');

Var ret = {};
For (var I = 0, len = searchHash. length; I <len; I ++) {// you can call the each method here
Var pair = searchHash [I];
If (pair = pair. split ('=') [0]) {
Var key = decodeURIComponent (pair. shift ());
Var value = pair. length> 1? Pair. join ('='): pair [0];
Console. log ()
If (value! = Undefined ){
Value = decodeURIComponent (value );
}
If (key in ret ){
If (ret [key]. constructor! = Array ){
Ret [key] = [ret [key];
}
Ret [key]. push (value );
} Else {
Ret [key] = value;
}
}
}
Return ret;
}
Console. dir (toQueryParams. call (linkURL ));


The above is basically the implementation of toQueryParams in Prototype. The above step is to use '=' to separate the parameter and then splice it in the value. In addition, substring can be used for implementation:

The Code is as follows:


Function toQueryParams (){
Var search = this. replace (/^ \ s +/, ''). replace (/\ s + $/,''). match (/([^? #] *) (#. *)? $ /);
If (! Search ){
Return {};
}
Var searchStr = search [1];
Var searchHash = searchStr. split ('&');

Var ret = {};
SearchHash. forEach (function (pair ){
Var temp = '';
If (temp = (pair. split ('=', 1) [0]) {
Var key = decodeURIComponent (temp );
Var value = pair. substring (key. length + 1 );
If (value! = Undefined ){
Value = decodeURIComponent (value );
}
If (key in ret ){
If (ret [key]. constructor! = Array ){
Ret [key] = [ret [key];
}
Ret [key]. push (value );
} Else {
Ret [key] = value;
}
}
});
Return ret;
}
Console. dir (toQueryParams. call (linkURL ));



1. Convert objects to URL query parameters

Converting an object to a URL query parameter requires a little effort. However, because it is converted to the query parameter form, only single-layer nested objects can be processed, and sub-objects cannot be processed. The principle is toQueryParams's reverse operation.

The Code is as follows:


Function toQueryPair (key, value ){
If (typeof value = 'undefined '){
Return key;
}
Return key + '=' + encodeURIComponent (value = null? '': String (value ));
}
Function toQueryString (obj ){
Var ret = [];
For (var key in obj ){
Key = encodeURIComponent (key );
Var values = obj [key];
If (values & values. constructor = Array) {// Array
Var queryValues = [];
For (var I = 0, len = values. length, value; I <len; I ++ ){
Value = values [I];
QueryValues. push (toQueryPair (key, value ));
}
Ret = ret. concat (queryValues );
} Else {// string
Ret. push (toQueryPair (key, values ));
}
}
Return ret. join ('&');
}
Console. log (toQueryString ({
Name: 'xesam ',
Age: 24
}); // Name = xesam & age = 24
Console. log (toQueryString ({
Name: 'xesam ',
Age: [24, 25, 26]
}); // Name = xesam & age = 24 & age = 25 & age = 26


The inject method is used in the real source code, but it is replaced in the Enumerable part.
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.