当前位置:网站首页>url转成obj或者obj转成url的方法
url转成obj或者obj转成url的方法
2022-08-11 00:36:00 【琴~~】
url转成obj或者obj转成url的方法
1、url转成obj
function urlToObj(url) {
if (typeof url !== 'string') return '请传入正确的参数类型'
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=小花
边栏推荐
猜你喜欢

百战RHCE(第四十八战:运维工程师必会技-Ansible学习3-构建Ansible清单)

英文文献阅读时,如何做笔记?
![[21 Days Learning Challenge] Half Insertion Sort](/img/30/4971479a2fa08592e88f032bb23844.png)
[21 Days Learning Challenge] Half Insertion Sort

HW-蓝队工作流程(1)

线上突然查询变慢怎么核查

Ali P7 bask in January payroll: hard to fill the, really sweet...

鲲鹏编译调试及原生开发工具基础知识

Jvm. Profiling tools (jconsole, jvisualvm, arthas, jprofiler, mat)

I caught a 10-year-old Ali test developer, and after talking about it, I made a lot of money...

BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文笔记
随机推荐
ArcGIS Pro 创建tpk
Single-chip human-computer interaction--matrix key
微信小程序通过URL Scheme动态的渲染数据
单片机人机交互--矩阵按键
Introduction to Qt (6) - Implementation of the lottery system
How engineers treat open source
J9 Digital Theory: DAO governance is more like an ecological process: governance is native to the network and continues to evolve
关于编程本质那些事
I caught a 10-year-old Ali test developer, and after talking about it, I made a lot of money...
Apache Commons Configuration Remote Code Execution Vulnerability (CVE-2022-33980) Analysis & Reproduction
Why do programming languages have the concept of variable types?
Shell Text Three Musketeers Sed
成功解决TypeError: can‘t multiply sequence by non-int of type ‘float‘
nodejs项目连接mysql数据库
【openpyxl】过滤和排序
分库分表ShardingSphere-JDBC笔记整理
详解JDBC的实现与优化(万字详解)
循环单词
Pico 4更多参数曝光:Pancake+彩色透视,还有Pro版本
容器技术真的是环境管理的救星吗?