通过正则表达式的方式
目标是获取问号后的数据,首先通过?将url分成两部分
const regex = /^([^\?]*)\?(.*)$/;
// ^([^\?]*) 匹配开头非问号的所有字符
// \? 以问号分隔
转换为对象
const url = 'http://www.baidu.com/code/?id=xxx&name=xxx?&sex=1';
let res = {};
const regex = /^([^\?]*)\?(.*)$/;
let result = regex.exec(url) || null
// 若无问号 数据则为空
const query = (result ? result[2] : '').trim()
console.log(query)
// > id=xxx&name=xxx?&sex=1
query.split('&').forEach(param => {
const parts = param.replace(/\+/g , '').split('=');
const key = decodeURIComponent(parts.shift())
const value = parts.length > 0 ? decodeURIComponent(parts.join('=')) : null
if(res[key] === undefined) {
res[key] = value
}
})
console.log(res)
// > {"id":"xxx","name":"xxx?","sex":"1"}
网友评论