convert URL Query String to Object All In One

convert URL Query String to Object All In One

URL / query string / paramas

query string to object

let str = "name=xgqfrms&sex=男&age=18&";

const params = new URLSearchParams(str);

for (let p of params) {
console.log(p);
} ["name", "xgqfrms"]
["sex", "男"]
["age", "18"]

filter

let str = "name=xgqfrms&sex=男&age=18&";

str = str.split(`&`).filter(item => item.length).join(`&`);
// "name=xgqfrms&sex=男&age=18" str.split(`&`).filter(item => item.length).reduce((acc, item) => {
const [key, value] = [...item.split(`=`)];
acc[key] = value;
}, {})

reduce

let str = "name=xgqfrms&sex=男&age=18&";

str = str.split(`&`).reduce((acc, item) => acc += item.length ? item : "", "");
// "name=xgqfrmssex=男age=18"

demo

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-01
* @modified
*
* @description string to object
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/ const log = console.log; const str = "name=xgqfrms&sex=男&age=18&"; const obj = str.split(`&`).filter(item => item.length).reduce((acc, item) => {
const [key, value] = [...item.split(`=`)];
acc[key] = value;
return acc;
}, {}) log(`obj =`, obj);
// obj = { name: 'xgqfrms', sex: '男', age: '18' }

refs

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array


convert URL Query String to Object All In One

xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


上一篇:今天开始学习php,粘一些重点放这以便查看记忆。


下一篇:node.js 访问sql server的 node_modules “msnodesql"的安装编译方法