preface

Select * from skill= basketball &year=2019; select * from skill= basketball &year=2019 This is where the regular expression comes in, and it looks like this:

Today we’ll take a look at the URLSearchParams interface that handles queries specifically for urls.

Simple to use

You just need to create a new instance of URLSearchParams.

let url = '? WLD = WLD = WLD = WLD = WLD = WLD = WLD = year;
let searchParams = new URLSearchParams(url);

for (let p of searchParams) {
  console.log(p);
}
// ["wd", "CAI Xukun "]
// ["skill", "skill"]
// ["year", "2019"]
Copy the code

Get a single field

What if NOW I just want to get the value of a single field? Just call this instance’s get method:

searchParams.get('wd') // "CAI Xukun"
searchParams.get('skill') // "basketball"
searchParams.get('year') / / "2019"
Copy the code

Sometimes you don’t know if a field exists, so you want to check it in advance. Use the has method of the example to determine:

searchParams.has('wd') // true
searchParams.has('age') // false
Copy the code

Add fields

The example provides the append method to add a field, which takes two arguments, key and value:

searchParams.append('age'.26);
searchParams.has('age'); // true
searchParams.get('age'); / / 26
Copy the code

Delete the field

Now that you don’t want the year field, just use delete.

searchParams.delete('year');
searchParams.has('year'); // false
Copy the code

Set the field

The set method is used when you want to rewrite a field rather than append it. For example, we think Kunge can sing, dance, and rap as well as basketball. Code:

searchParams.set('skill'.'Basketball singing and rap');
Copy the code

Convert to string

After modifying the instance, sometimes you need to convert it to a string to redirect the route, etc., using the toString method

searchParams.toString(); // "wd= skill +rap&year=2019&age=26"
Copy the code

After a wave of operations

compatibility

Modern browsers are basically fine, but IE support is not ideal.

Outside the chain

  • MDN reference
  • Check out the blog at jser.tech