当前位置:网站首页>How to convert url to obj or obj to url
How to convert url to obj or obj to url
2022-08-11 00:51:00 【piano~~】
url转成obj或者obj转成url的方法
1、url转成obj
function urlToObj(url) {
if (typeof url !== 'string') return 'Please pass in the correct parameter type'
const urlArr = url.split('?');
let obj = {
};
let params = {
};
if (urlArr?.length) {
urlArr.forEach((item, index) => {
if (!index) return obj.path = item;
const itemArr = item?.split('&');
itemArr.forEach(it => {
if (it) {
const itArr = it.split('=');
if (itArr[0]) params[itArr[0]] = itArr[1];
}
})
})
}
obj.query = params;
return obj
}
使用:
const a = urlToObj('http:baidu.com?age=1&sex=nan')
console.log(a);//{path: 'http:baidu.com', query: {…}}
2、obj转成url
function objToUrl(url) {
let newUrl = '';
if (url?.path) newUrl = url.path + '?';
if (url?.query) {
for (let key in url?.query) {
newUrl += `${
key}=${
url?.query[key]}&`
}
}
return newUrl.slice(0, newUrl?.length - 1)
}
使用:
const b = objToUrl({
path: 'http:baidu.com',
query: {
age: 11,
name: '小花'
}
})
console.log(b)//http:baidu.com?age=11&name=小花
边栏推荐
- SAP ABAP JSON 格式数据处理
- C# JObject解析JSON数据
- 双机热备综合实验(VRRP+OSPF+VTP+NAT+DHCP+PVSTP+单臂路由)
- [21-day learning challenge - kernel notes] (5) - devmem read and write register debugging
- 分库分表ShardingSphere-JDBC笔记整理
- 91.(cesium之家)cesium火箭发射模拟
- More parameter exposure of Pico 4: Pancake + color perspective, and Pro version
- Single-chip human-computer interaction--matrix key
- 详解JDBC的实现与优化(万字详解)
- [Excel knowledge and skills] Convert "false" date to "true" date format
猜你喜欢
随机推荐
版本号大小的判断方法
Navicat 16-数据库工具
虚拟电厂可视化大屏,深挖痛点精准减碳
More parameter exposure of Pico 4: Pancake + color perspective, and Pro version
Elastic scaling of construction resources
postgresql参数意义
MSTP——多生成树(案列+配置)
Volatile和CAS
J9 Digital Theory: DAO governance is more like an ecological process: governance is native to the network and continues to evolve
【经典排序】快速排序
SystemVerilog: 验证知识点点滴滴
力扣------使用最小花费爬楼梯
vim simple save window id
Some Experiences of Embedded Software Logging
【21天学习挑战赛】折半插入排序
【服务器数据恢复】raid5崩溃导致lvm信息和VXFS文件系统损坏的数据恢复案例
全排列思路详解
Jvm. Profiling tools (jconsole, jvisualvm, arthas, jprofiler, mat)
YOLOv5的Tricks | 【Trick12】YOLOv5使用的数据增强方法汇总
【考虫 六级英语】语法课笔记