In the comments on the tools and methods article, someone mentioned the URLSearchParams URL object interface. Since I haven’t touched with it before, I searched for specific uses and found that the function of this interface is very practical. I hereby sort out and share it with you.

What is URLSearchParams

The URLSearchParams interface defines some useful methods for handling query strings for urls. With reference to

Thus, we can see that it is used to handle URL correlation. What are the functions?

Interface methods

First, we call new URLSearchParams() to return an instance of the URLSearchParams object. Under this instance we can call the following methods:

Append (name, value): Inserts a specified key/value pair as the new search parameter. Name is the key name of the search parameter to be inserted, and value is the corresponding value of the search parameter to be inserted.

let url = new URL('https://example.com?foo=1&bar=2');
letparams = new URLSearchParams(url.search.slice(1)); // Add the second foo search parameter. params.append('foo', 4);
params.toString();
// 'foo=1&bar=2&foo=4'
Copy the code

Delete (name): Deletes the specified search parameter and its value from the search parameter list. Name is the name of the key value to be deleted.

let url = new URL('https://example.com?foo=1&bar=2');
letparams = new URLSearchParams(url.search.slice(1)); // Add the second foo search parameter. params.delete('foo');
params.toString();
// 'bar=2'
Copy the code

Entries (): Returns an object that iterator can traverse through all key/value pairs.

// Create a test URLSearchParams objectlet searchParams = new URLSearchParams("key1=value1&key2=value2"); // Displays key/value pairsfor(var pair of searchParams.entries()) {
   console.log(pair[0]+ ', '+ pair[1]); 
}

// key1, value1
// key2, value2
Copy the code

Get (name): Gets the first value of the specified search parameter. Name is the key name of the parameter to be returned. Return a USVString; If not, null is returned. If a page URL is https://example.com/?name=Jonathan&age=18, you can parse the parameters name and age like this:

let params = new URLSearchParams(document.location.search.substring(1));
let name = params.get("name"); // is the string "Jonathan"
let age = parseInt(params.get("age"), 10); // is the number 18 // return null if the key name does not exist:let address = params.get("address"); // null
Copy the code

GetAll (name): Gets all the values of the specified search parameter, and returns an array. Name is the name of the returned parameter.

let url = new URL('https://example.com?foo=1&bar=2'); 
letparams = new URLSearchParams(url.search.slice(1)); // Add the second value params.append('foo', 4);

console.log(params.getAll('foo'))'// output ["1","4"].Copy the code

Has (name): Returns Boolean to determine whether this search parameter exists. Name is the key name of the parameter we want to query.

let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));

params.has('bar') = = =true; //true
Copy the code

Keys (): Returns iterator this object contains all the key names of the key/value pairs.

// Create a test URLSearchParams objectlet searchParams = new URLSearchParams("key1=value1&key2=value2"); // Outputs key-value pairsfor(var key of searchParams.keys()) { 
  console.log(key); 
}

// key1
// key2
Copy the code

Set (name, value): Sets a new value for a search parameter. If there are more than one value, all other values will be deleted. Where name is the key name of the modified parameter to be inserted, and value is the new value of the search parameter to be inserted.

let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));

//Add a third parameter.
params.set('baz', 3);
Copy the code

Sort (): sort key names.

// Create a test URLSearchParams object 
let searchParams = new URLSearchParams("c=4&a=2&b=3&a=1"); 

// Sort the key/value pairs
searchParams.sort();

// Display the sorted query string
console.log(searchParams.toString());

// a=2&a=1&b=3&c=4
Copy the code

ToString (): Returns a string of search parameters that can be used directly on the URL.

let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));

//Add a second foo parameter.
params.append('foo', 4);
console.log(params.toString());
//Prints 'foo=1&bar=2&foo=4'.
Copy the code

Values (): Returns iterator this object contains all the values of key/value pairs.

// Create a test URLSearchParams objectlet searchParams = new URLSearchParams("key1=value1&key2=value2"); / / the output valuefor(var value of searchParams.values()) {
  console.log(value);
}
Copy the code

The above is an overview of all its interface methods. However, it doesn’t seem to have much to do with our normal life. Let’s look at some specific usage scenarios.

Usage scenarios

Scenario 1 Obtaining browser address parameters

We used to get browser address parameters a lot of times by splitting the address and then concatenating field objects, similar

function GetRequest() {
  leturl = location.search; // Get the url"?"The string following the characterlet theRequest = new Object();
  if (url.indexOf("?")! = 1) {let str = url.substr(1);
    strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
    }
  }
  return theRequest;
}
Copy the code

But if we use URLSearchParams, we don’t have to do this

const params = new URLSearchParams(location.search)
params.get(key)
Copy the code

Use URLSearchParams to process the data sent by AXIOS

When we use AXIos and FETCH to make data requests instead of ajax, we encounter inconsistent data formats.

axios({
    method: 'post',
    url: '/test',
    data: {
        name: 'li lei',
        age: 18
    }
})
Copy the code

The above call method is very similar to what we would normally write with Ajax, but we’ll notice that the default data format is different:

Axios data format:

Ajax data format:

Yes, there is an extra layer of wrapping, which makes it difficult to connect to our back end. Even manually changing the ContentType to Application/X-www-form-urlencoded was still unresolved.

So how does URLSearchParams solve this

let params = new URLSearchParams();
params.append('name'.'li lei');
params.append('age', 18);

axios({
    method: 'post',
    url: '/test',
    data: params
})
Copy the code

Compatibility Solution

The tools are good, but the inevitable compatibility is less than ideal. So what are we going to do?

To do a good job, he must sharpen his tools

url-search-params-polyfill

This is a Polyfill library made specifically for URLSearchParams. Specific use method we can refer to the relevant description of the library. Again, this library solves browser compatibility issues, but we still need to manually set the value of ContentType when using fetch. Reference an instance given in the library

function myFetch(url, { headers = {}, body }) {
    headers = headers instanceof Headers ? headers : new Headers(headers);
    
    if (body instanceof URLSearchParams) {
        headers.set('Content-Type'.'application/x-www-form-urlencoded; charset=UTF-8');
    }
    
    fetch(url, {
        headers,
        body
    });
}
Copy the code

summary

Through our description of the official interface and the use of actual scenarios, we have a detailed understanding of the main functions and use methods of URLSearchParams, hoping to play a helpful role in our future development.


Resources: URLSearchParams API uses URLSearchParams to process data sent by AXIOS


Follow the wechat public account to push updates synchronously

Or you can goGithubI put a Star on it