How to convert URL parameters to a JavaScript object?

前端 未结 30 1382
时光取名叫无心
时光取名叫无心 2020-11-22 13:57

I have a string like this:

abc=foo&def=%5Basf%5D&xyz=5

How can I convert it into a JavaScript object like this?

{
          


        
30条回答
  •  耶瑟儿~
    2020-11-22 14:35

    One of the simplest way to do this using URLSearchParam interface.

    Below is the working code snippet:

    let paramObj={},
        querystring=window.location.search,
        searchParams = new URLSearchParams(querystring);    
    
      //*** :loop to add key and values to the param object.
     searchParams.forEach(function(value, key) {
          paramObj[key] = value;
       });
    

提交回复
热议问题