URLSearchParams converts JavaScript data types into a URL-encoded string

Query transmitted as part of the URL cannot contain specific characters. It must therefore be transmitted with URL encoding.

Thankfully, we can use URLSearchParams to convert a ordinary string, object or array into a URL-encoded string with appropriate seperators (&).

const params = {
    name: 'Mervin Bratic',
    height: 193,
}

const URLencodedString = new URLSearchParams(params).toString();
console.log(URLencodedString) // 'name=Mervin+Bratic&height=193'

4 januari 2023