将url的参数解析为Json数据


代码如下:

<!DOCTYPE>
<html lang="en">
  <head>
  </head>
  <body>
  <body>
  <script>
    var url = 'https://www.baidu.com/s?wd=javascript&rsv_spt=1';
    window.onload = function () {
       method2(url);
    };
    
    function method1(url) {
      // 使用正则来 两边的参数不可能是 &=? 所以去反集[^&=?]
      let regex = /([^&=?]+)=([^&=?]+)/g,
      obj = {};
      url.replace(regex, (...arg) => {
        obj[arg[1]] = arg[2];
      });
      console.log(obj);
    }
    
    
    function method2(url) {
      let index = url.indexOf('?');
      let datas = url.substring(index+1, url.length).split('&');
      let obj = {};
      for (let item of datas) {
        let data = item.split('=')
        obj[data[0]] = data[1];
      }
      console.log(obj);
    }
    
  </script>
</html>

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM