Front-end must know will be - black & operation of the URL

Foreword

Now there is such a URL:? Www.baidu.com/s wd = Cai Xu Kun & skill = basketball & year = 2019, how to get the field on the query it? At this time the regular expression comes in handy, the effect is as:

Overkill it, in today's learn designed to handle the URL query interface: URLSearchParams.

Simple to use

Only needs a new instance can URLSearchParams code:

let url = '?wd=蔡徐坤&skill=篮球&year=2019';
let searchParams = new URLSearchParams(url);

for (let p of searchParams) {
  console.log(p);
}
// ["wd", "蔡徐坤"]
// ["skill", "篮球"]
// ["year", "2019"]
复制代码

Get a single field

If now I just want to get the value of a single field, how to do it? Only you need to call this method to get the instance, Code:

searchParams.get('wd') // "蔡徐坤"
searchParams.get('skill') // "篮球"
searchParams.get('year') // "2019"
复制代码

Sometimes I do not know whether there is a field, so I wanted to check in advance under. Examples of the method used has to judge the code:

searchParams.has('wd') // true
searchParams.has('age') // false
复制代码

Add field

Append example provides methods to add the field, this method takes two parameters, the former is a key, which is the value, the code:

searchParams.append('age', 26);
searchParams.has('age'); // true
searchParams.get('age'); // 26
复制代码

Delete field

Now I do not want to field a year, you can directly delete the code:

searchParams.delete('year');
searchParams.has('year'); // false
复制代码

Setting field

Sometimes want to override a field, instead of adding (append) a field, this time need to use the set method, for example, we feel Kun brother will not only basketball, but also sing, dance, rap. Code:

searchParams.set('skill', '篮球 唱 跳 rap');
复制代码

Into a string

After the modified example, sometimes need to turn the string, routing jumps, etc., using methods toString

searchParams.toString(); // "wd=蔡徐坤&skill=篮球+唱+跳+rap&year=2019&age=26"
复制代码

After a wave of Operation

compatibility

What modern browsers basically no big problem, but IE support is not very satisfactory.

Outside the chain

Reproduced in: https: //juejin.im/post/5d038c9051882548ac439933

Guess you like

Origin blog.csdn.net/weixin_33774615/article/details/93164520