Home > Web Front-end > JS Tutorial > Instructions for using the querystring.parse method in node.js_node.js

Instructions for using the querystring.parse method in node.js_node.js

WBOY
Release: 2016-05-16 16:27:48
Original
1893 people have browsed it

Method description:

Convert string to object. To put it bluntly, it actually converts the parameter string on the url into an array object. (You’ll know just by looking at the example)

Grammar:

Copy code The code is as follows:

querystring.parse(str, [sep], [eq], [options])

Receive parameters:

str The string to be converted

sep Set the delimiter, the default is ‘&’

eq Set the assignment character, the default is ‘=’

[options] maxKeys The maximum length of acceptable strings, the default is 1000

Example:

Copy code The code is as follows:

querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }

Source code:

Copy 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 should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; i) {
var x = qs[i].replace(regexp, ' '),
​​​​ 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;
};

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template