UNPKG

qs-like

Version:

A tiny query string parsing and stringifying library

148 lines (131 loc) 3.35 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 isObject from 'celia/isObject'; import forOwn from 'celia/_forOwn'; function unescape (str) { return decodeURIComponent(str); } 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; } // rfc3986 var encodeReserveRE = /[!'()*]/g; function encodeReserveReplacer(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); } function escape (str) { return encodeURIComponent(str) .replace(encodeReserveRE, encodeReserveReplacer); } var stringify = JSON.stringify; function convert(value, encode) { switch (typeof value) { case 'string': return encode(value); case 'number': if (isNaN(value)) { return ''; } case 'boolean': return value.toString(); case 'object': return value === null ? '' : encode(stringify(value)); case 'undefined': return ''; // case 'function': // return encode(value.toString()); default: return encode(value.toString()); } } var isArray$1 = Array.isArray; function stringify$1 (obj, sep, eq, options) { if (isObject(obj)) { sep = sep || '&'; eq = eq || '='; options = options || {}; var encode = options.encodeURIComponent || escape; var arr = []; forOwn(obj, function (value, key) { if (key) { if (isArray$1(value)) { value.forEach(function (val) { append(arr, key + eq + convert(val, encode)); }); } else { append(arr, key + eq + convert(value, encode)); } } }); return arr.join(sep); } return ''; } function prefix (str, prefix) { prefix = prefix || '?'; return str ? str.indexOf(prefix) === 0 ? str : (prefix + str) : str; } export { parse$1 as decode, stringify$1 as encode, escape, parse$1 as parse, prefix, stringify$1 as stringify, unescape };