当前位置:网站首页>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=小花
边栏推荐
猜你喜欢
随机推荐
url转成obj或者obj转成url的方法
使用 BeanUtils 做属性拷贝,性能有点拉胯!
版本号大小的判断方法
详谈二叉搜索树
SystemVerilog: 验证知识点点滴滴
循环单词
SQL statement--get database table information, table name, column name, description comment, etc.
MSTP——多生成树(案列+配置)
R language multiple linear regression, ARIMA analysis of the impact of different candidates in the United States on the economic GDP time series
C# using timer
微信小程序通过URL Scheme动态的渲染数据
Some Experiences of Embedded Software Logging
分库分表ShardingSphere-JDBC笔记整理
Shell 文本三剑客 Sed
22/8/9 Collection of Greedy Problems
时间戳转换为日期格式、获取当前时间戳
详解JDBC的实现与优化(万字详解)
Which foreign language journals and conferences can be submitted for software engineering/system software/programming language?
WinForm(五)控件和它的成员
MySQL进阶查询








