Last updated: Mar 4, 2024
Reading timeยท5 min
Use the URLSearchParams()
constructor to convert an object to a query
string.
Calling the toString()
method on the result returns a query string without
the question mark. If the provided object is empty, an empty string is
returned.
const obj = { page: 2, limit: 10, filter: 'js', }; const result = '?' + new URLSearchParams(obj).toString(); console.log(result); // ๐๏ธ "?page=2&limit=10&filter=js"
If you need to convert a query string to an object, click on the following subheading.
We passed an object to the URLSearchParams()
constructor and called the
toString()
method on the result.
The URLSearchParams class returns an object that is used to work with the query string of a URL.
URLSearchParams.toString()
method returns a query string without the question mark.We used the addition (+) operator to prepend a question mark to the result to make it a valid query string.
This is a four-step process:
Object.keys()
method to get an array of the object's keys.map()
method to iterate over the array.&
symbol.const obj = { page: 2, limit: 10, filter: 'js', }; const str = '?' + Object.keys(obj) .map(key => { return `${key}=${encodeURIComponent(obj[key])}`; }) .join('&'); console.log(str); // ๐๏ธ "?page=2&limit=10&filter=js"
The Object.keys() method returns an array of the object's keys.
const obj = { page: 2, limit: 10, filter: 'js', }; // ๐๏ธ ['page', 'limit', 'filter'] console.log(Object.keys(obj));
The next step is to use the Array.map() method to iterate over the array of keys.
map()
method gets called with each element in the array.On each iteration, we return a string in the form of key=value
.
We used the encodeURIComponent() function to encode the query parameter values.
This basically replaces characters like ?
, =
, &
with escape sequences to
produce a more consistent query string.
We used the Array.join() method to join the array of strings with an ampersand separator.
const arr = ['page=2', 'limit=10', 'filter=js']; // ๐๏ธ "page=2&limit=10&filter=js" console.log(arr.join('&'));
The only argument the Array.join()
method takes is a separator
- the string
used to separate the elements of the array.
The last step is to prepend a question mark to the result to form a valid query string.
Use the URLSearchParams
constructor to convert a query string to an
object.
The constructor returns an object instance from which we can access the query
string parameters using the get()
method, e.g. obj.get('page')
.
const queryString = '?page=3&filter=js'; const obj = new URLSearchParams(queryString); // โ Get query parameters from the object console.log(obj.get('page')); // ๐๏ธ "3" console.log(obj.get('filter')); // ๐๏ธ "js" // โ Check if object contains query parameter console.log(obj.has('page')); // ๐๏ธ true console.log(obj.has('test')); // ๐๏ธ false // โ Set new query parameters on the object obj.set('limit', 10); console.log(obj.get('limit')); // ๐๏ธ "10" // โ Get the Query String equivalent of the object // ๐๏ธ "page=3&filter=js&limit=10" console.log(obj.toString());
You can use the window.location.search
property to get the query string that
has to be passed to the URLSearchParams
constructor.
const obj = new URLSearchParams(window.location.search); console.log(obj.get('page')); // ๐๏ธ "3" console.log(obj.get('filter')); // ๐๏ธ "js"
The search
property returns a string containing a ?
followed by the
parameters of the URL, e.g. ?page=123
.
The URLSearchParams class takes a query string as a parameter, but if you have an entire URL, you can use this approach instead.
const url = new URL('https://bobbyhadz.com?page=3&filter=js'); const obj = new URLSearchParams(url.search); console.log(obj.get('page')); // ๐๏ธ "3" console.log(obj.get('filter')); // ๐๏ธ "js"
The URL()
constructor returns a newly created URL
object that represents the URL it got
passed as a parameter.
If you want to convert the URLSearchParams
object to a native JavaScript
object, pass the object instance to the Object.fromEntries
method.
// โ If you have Query String const queryString = '?page=3&filter=js'; const obj1 = Object.fromEntries( new URLSearchParams(queryString), ); // ๐๏ธ {page: '3', filter: 'js'} console.log(obj1); // ---------------------------------------------------- // โ If you have entire URL const url = new URL('https://example.com?page=3&filter=js'); const obj2 = Object.fromEntries(new URLSearchParams(url.search)); // ๐๏ธ {page: '3', filter: 'js'} console.log(obj2);
However, you probably don't need to convert the return value of the
URLSearchParams
constructor to a native object as it implements many
convenient methods.
The
URLSearchParams.get
method takes the name of the query parameter and returns the corresponding value
if the parameter is found, otherwise null
is returned.
const obj = new URLSearchParams(window.location.search); console.log(obj.get('page')); // ๐๏ธ "3" console.log(obj.get('filter')); // ๐๏ธ "js"
Note that the value returned from the get()
method has a type of string
.
If you need to convert the value to a number, you can pass it to the Number()
constructor, e.g. const pageNum = Number(page);
.
If you need to check whether the query parameter is contained in the object, you can use the URLSearchParams.has method.
const obj = new URLSearchParams(window.location.search); console.log(obj.has('page')); // ๐๏ธ true console.log(obj.has('test')); // ๐๏ธ false
The method takes the name of the parameter and returns true
if the parameter
is present and false
otherwise.
You can use the URLSearchParams.set method if you need to add query parameters to the object.
const obj = new URLSearchParams(window.location.search); obj.set('limit', 10); console.log(obj.get('limit')); // ๐๏ธ "10"
The set()
method takes 2 parameters:
When you need to get the equivalent query string, you just need to call the URLSearchParams.toString() method.
const obj = new URLSearchParams(window.location.search); // ๐๏ธ page=123&limit=10 console.log(obj.toString());
Note that the toString()
method returns a query string without the question
mark.
You would probably have to add the question mark if appending the result to a URL.
const obj = new URLSearchParams(window.location.search); // ๐๏ธ "page=3&filter=js&limit=10" console.log(obj.toString()); const withQuestionMark = '?' + obj.toString(); // ๐๏ธ "?page=2&filter=js&limit=10" console.log(withQuestionMark);
The object that the URLSearchParams()
constructor returns implements many of
the commonly used array methods, e.g. keys()
, values()
and forEach()
.
const queryString = '?page=3&filter=js'; const obj = new URLSearchParams(queryString); const keys = obj.keys(); console.log(keys); // ๐๏ธ (iterator) {'page', 'filter'} const values = obj.values(); console.log(values); // ๐๏ธ (iterator) {'3', 'js'}
If you need to iterate over the object, use the URLSearchParams.forEach method.
const queryString = '?page=3&filter=js'; const obj = new URLSearchParams(queryString); obj.forEach((value, key) => { console.log(value); // ๐๏ธ "3", "js" console.log(key); // ๐๏ธ "page", "filter" });
The forEach
method takes a function and invokes it for every key-value pair in
the object of query parameters.
The first parameter the function is passed is the value and the second is the key of the query parameter.
You can learn more about the related topics by checking out the following tutorials: