Are You Still Use "+=" To Add Query Dynamically? Use URLSearchParams()!

Introduction

We usually added query dynamically by using +=. However, it is not easily manageable when it comes to long query string. In this case, there is URLSearchParams for easily manage the query dynamically.

using +=

let url = `https://github.com/vannskang?test1=T1&`;
let param1 = 'test2=T2&test3=T3';
let param2 = 'test4=T4';

// condition
if (isParam1Required) url += param1; // https://github.com/vannskang?test1=T1&test2=T2&test3=T3
if (isParam2Required) url += param2; // https://github.com/vannskang?test1=T1&test4=T4

It’s simple but you have to careful about & or key, value matching. Becuase It is just string and you can’t handle except checking directly.

Let’s check the using URLSearchParams example below.

using URLSearchParams()

const params = new URLSearchParams({
	test1: 'T1',
});

// https://github.com/vannskang?test1=T1&test2=T2&test3=T3
if (isParam1Required) {
	params.append('test2', 'T2');
	params.append('test3', 'T3');
}

// https://github.com/vannskang?test1=T1&test4=T4
if (isParam2Required) params.append('test4', 'T4');

const URL = `https://github.com/vannskang?${params.toString()}`;

Conclusion

It is very simple to use for adding query dynamically with URLSearchParams, but it is more efficient way and easier to figure out for the cases required to add more query string.