UNPKG

qs-like

Version:

A tiny query string parsing and stringifying library

72 lines (66 loc) 1.64 kB
/* * qs-like.js v1.0.1 * (c) 2018-2019 Jesse Feng * Released under the MIT License. */ import append from 'celia/_append'; import isString from 'celia/isString'; import isUndefined from 'celia/isUndefined'; import forEach from 'celia/_forEach'; import unescape from './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; } export default parse$1;