This article mainly introduces node. querystring. description of the parse method. This document describes querystring. parse method description, syntax, receive parameters, use instances, and implement Source Code. For more information, see
Method description:
Converts a string to an object. To put it bluntly, the parameter string on the url is converted into an array object. (See the example)
Syntax:
The Code is as follows:
Querystring. parse (str, [sep], [eq], [options])
Receiving parameters:
Str string to be converted
Set the separator for sep. The default value is '&'
The eq value assignment operator. The default value is '='
[Options] maximum length of a maxKeys acceptable string, 1000 by default
Example:
The Code is as follows:
Querystring. parse ('foo = bar & baz = qux & baz = quux & corge ')
// Returns
{Foo: 'bar', baz: ['qux', 'quux '], corge :''}
Source code:
The Code is as follows:
// Parse a key = val string.
QueryString. parse = QueryString. decode = function (qs, sep, eq, options ){
Sep = sep | '&';
Eq = eq | '= ';
Var obj = {};
If (! Util. isString (qs) | qs. length = 0 ){
Return obj;
}
Var regexp =/\ +/g;
Qs = qs. split (sep );
Var maxKeys = 1000;
If (options & util. isNumber (options. maxKeys )){
MaxKeys = options. maxKeys;
}
Var len = qs. length;
// MaxKeys <= 0 means that we shocould not limit keys count
If (maxKeys> 0 & len> maxKeys ){
Len = maxKeys;
}
For (var I = 0; I <len; ++ I ){
Var x = qs [I]. replace (regexp, '% 20 '),
Idx = x. indexOf (eq ),
Kstr, vstr, k, v;
If (idx> = 0 ){
Kstr = x. substr (0, idx );
Vstr = x. substr (idx + 1 );
} Else {
Kstr = x;
Vstr = '';
}
Try {
K = decodeURIComponent (kstr );
V = decodeURIComponent (vstr );
} Catch (e ){
K = QueryString. unescape (kstr, true );
V = QueryString. unescape (vstr, true );
}
If (! HasOwnProperty (obj, k )){
Obj [k] = v;
} Else if (util. isArray (obj [k]) {
Obj [k]. push (v );
} Else {
Obj [k] = [obj [k], v];
}
}
Return obj;
};