Extract parameters from URLs and convert objects to URL query parameters

Source: Internet
Author: User

These two methods mainly supplement the toquerystring method of toqueryparams and object in the sring section previously skipped in prototype analysis.

 

1. Extract parameters from URLs

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:

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']}

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];

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:

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.

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

 

For more information, see http://www.cnblogs.com/xesam /]
Address: http://www.cnblogs.com/xesam/archive/2012/01/12/2320068.html

The inject method is used in the real source code, but it is replaced in the enumerable part.

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.