qs-like
Version:
A tiny query string parsing and stringifying library
74 lines (67 loc) • 1.67 kB
JavaScript
/*
* qs-like.js v1.0.1
* (c) 2018-2019 Jesse Feng
* Released under the MIT License.
*/
;
var append = require('celia/_append');
var isString = require('celia/isString');
var isUndefined = require('celia/isUndefined');
var forEach = require('celia/_forEach');
var _unescape = require('./unescape.js');
function parse(str, sep, eq, cb) {
var matchedKey = '';
var matchedValue = '';
var hasEq = false;
forEach(str, function (c) {
switch (c) {
case '?':
matchedKey = '';
matchedValue = '';
return;
case sep:
hasEq && matchedKey &&
cb(matchedKey, matchedValue);
hasEq = false;
matchedKey = '';
matchedValue = '';
return;
case eq:
hasEq = true;
matchedValue = '';
return;
case '#':
return false;
default:
!hasEq
? (matchedKey += c)
: (matchedValue += c);
}
});
hasEq && matchedKey &&
cb(matchedKey, matchedValue);
}
var isArray = Array.isArray;
function parse$1 (str, sep, eq, options) {
var result = {};
if (isString(str)) {
sep = sep || '&';
eq = eq || '=';
options = options || {};
var decode = options.decodeURIComponent || _unescape;
parse(str, sep, eq, function (key, value) {
value = decode(value);
var last = result[key];
// 没有相同的key值
if (isUndefined(last)) {
result[key] = value;
} else if (isArray(last)) { // 继续追加
append(last, value);
} else { // 已存在key
result[key] = [last, value];
}
});
}
return result;
}
module.exports = parse$1;