huabingtao / front-knowledge

基于Issues系统学习前端技术
0 stars 0 forks source link

使用正则表达式解析URL #89

Open huabingtao opened 3 weeks ago

huabingtao commented 3 weeks ago
// 简单的做法
const getUrlQueryParams = (url) => {
    const res = {};
    const reg = /([^?&]*)=([^&#]*)/g;
    const paramObj = url.match(reg);
    for (key in paramObj) {
      const paramArray = paramObj[key].split("=")
      res[paramArray[0]] = paramArray[1]
    }
    return res
}
const url = "https://www.example.com/path/to/page?query=123&value=abc&empty=&another=value"
const paramsObj = getUrlQueryParams(url)
console.log(paramsObj)

// 严谨的获取url参数方法
const getUrlParams = (url) => { 
  if(!isUrl(url)) return false
  const params = {}
  // 设置正则表达式键值对
  const reg = /([?&])([^&=#]+)=([^&#]*)/g; 
  let match = {}
  // 当exec不为空的时候执行循环
  // exec匹配返回数组 1.完全匹配的字符串 2.捕获组(从索引 1 开始)
  // 我们需要的是key和value所以从2 3获取
  while((match = reg.exec(url)) !== null){
      const key =   decodeURIComponent(match[2]) 
    const value = decodeURIComponent(match[3])
    // 判断是否为数组
    if(value.startsWith('[') && value.endsWith(']')){
        params[key] = value.slice(1, -1).split(',').map(v => v.trim());
    }else{
        params[key] = value
    }
  }
  return params  
}
const params = getUrlParams("https://be2m999k9z.feishu.cn/docx/XuAVdTch0oKcuWxIkoXc80PKncc?a=1&b=2&c=[3,4,5]")
console.log('getUrlParams:',params)