Created
June 1, 2021 09:48
-
-
Save yeyuguo/893cdcbe57fa51efdccc90b1705c77e0 to your computer and use it in GitHub Desktop.
格式化 url 字符为对象
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parseStrParam(url) { | |
const paramsStr = /.+\?(.+)$/.exec(url)[1] // 将 ? 后面的字符串取出来 | |
const paramsArr = paramsStr.split('&') // 将字符串以 & 分割后存到数组中 | |
let paramsObj = {} | |
// 将 params 存到对象中 | |
paramsArr.forEach(param => { | |
if (/=/.test(param)) { // 处理有 value 的参数 | |
let [key, val] = param.split('=') // 分割 key 和 value | |
val = decodeURIComponent(val) // 解码 | |
val = /^\d+$/.test(val) ? parseFloat(val) : val // 判断是否转为数字 | |
val = /^(\{|\[).*(\}|\])$/.test(val) ? JSON.parse(val) : val // 解析 字符对象 | |
if (paramsObj.hasOwnProperty(key)) { // 如果对象有 key,则添加一个值 | |
paramsObj[key] = [].concat(paramsObj[key], val) | |
} else { // 如果对象没有这个 key,创建 key 并设置值 | |
paramsObj[key] = val | |
} | |
} else { // 处理没有 value 的参数 | |
paramsObj[param] = true | |
} | |
}) | |
return paramsObj | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment