Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Sometimes the request parameter is placed in the query of the interface. After the front-end end gets the link, if it needs to obtain the data in the parameter, the front-end needs to parse the API, and then obtain the parameter and obtain the value.

Parse queryString in URL

Input scenario:

The URL is as follows, which contains several parameters, and the interface is encoded

url = https://www.baidu.com?name=coder&age=20&callback=https%3A%2F%2Fbaidu.com%3Fname%3Dtest&list[]=a&json=%7B%22str%22%3A%22a bc%22,%22num%22%3A123%7D

Expected output:

All query parameters are retrieved to form an object.

 {
     name: "coder",
     age: "20",
     callback: "https://baidu.com?name=test",
     list: ["a"],
     json: {
           str: 'abc',
           num: 123
     }
 }
Copy the code

Analysis of the problem solving

  1. urlIt’s coded, so it’s got to be righturlDecrypt: usedecodeURIComponent()

DecodeURIComponent ()

  1. The string is split with & to get an array

  2. Get rid of the first value in the array? In front of the character

  3. Iterate through the number group to obtain the corresponding key and value

    • Parameter of array type, which requires special handling
    • Parameters of object types also require special handling

The problem solving

The complete code is as follows:

Function queryString(url) {const decodeUrl = decodeURIComponent(url); // Let paramArrays = decodeurl.split ('&'); ParamArrays [0] = paramArrays[0].split('? '); paramArrays[0].shift(); paramArrays[0] = paramArrays[0].join('? '); console.log('paramArrays: ', paramArrays) // Define an empty object to receive keys and value const obj = {} paramArrays. ForEach (ele => {const itemArr = ele. Split ('='); let key = itemArr[0] let val = itemArr[1]; let arr = []; if(key.includes('[]')){ key = key.replace('[]', ''); arr.push(val); val = arr; } else if (val.indexOf('{') === 0) { val = JSON.parse(val) } obj[key] = val; }) console.log(obj)} // Execution result console.log(queryString('https://www.baidu.com?name=coder&age=20&callback=https%3A%2F%2Fbaidu.com%3Fname%3Dtest&list[]=a &json=%7B%22str%22%3A%22abc%22,%22num%22%3A123%7D'))Copy the code

conclusion

If this article helped you, please like 👍 and follow ⭐️.

If there are any errors in this article, please correct them in the comments section 🙏🙏.