您的当前位置:首页正文

前端解析URL的两种方式

2024-12-02 来源:个人技术集锦

方法一:利用 splice 分割 + 循环依次取出

方法一:
function queryURLparams(url) {
    let obj = {}
    if (url.indexOf('?') < 0) return obj
    let arr = url.split('?')
    url = arr[1]
    let array = url.split('&')
    for (let i = 0; i < array.length; i++) {
        let arr2 = array[i]
        let arr3 = arr2.split('=')
        obj[arr3[0]] = arr3[1]
    }
    return obj

}
方法二:
  function getURL(url){
      let str = url.split("?")[1];
      let str1 = str.split("&");
      let obj = {};
      for(let i = 0; i<str1.length; i++){
          let str2 = str1[i].split("=");
          let key = str2[0];
          let value = str2[1];
          obj[key] = value;

      }
      return obj;
  }
  console.log(getURL(url))

方法二: 正则 + arguments

function queryURLparamsRegEs5(url) {
    let obj = {}
    let reg = /([^?=&]+)=([^?=&]+)/g
    url.replace(reg, function() {
        obj[arguments[1]] = arguments[2]
    })
    return obj
}

显示全文