將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