JavaScript - Converting Query String to Object with Null, Undefined, and Boolean Values
Last Updated :
02 Dec, 2024
Here are the different methods to convert query string to object with null, undefined and boolean values.
1. Using URLSearchParams API
The URLSearchParams interface provides an easy and modern way to work with query strings. It lets you easily parse the query string and convert it into a JavaScript object while handling null and undefined values.
JavaScript
function strToObj(q) {
const param = new URLSearchParams(q);
let obj = {};
for (let [key, val] of param.entries()) {
obj[key] = val === "null"
? null
: val === "undefined"
? undefined
: val === "true"
? true
: val === "false"
? false
: val;
}
return obj;
}
const q = "?name=Rahul&age=30&isAdmin=true&city=null";
const res = strToObj(q);
console.log(res);
Output{ name: 'Rahul', age: '30', isAdmin: true, city: null }
- URLSearchParams(q) converts the query string into a URLSearchParams object.
- params.entries() iterates over each key-value pair.
- The check for "null", "undefined", "true", and "false" is done to handle special cases like null and booleans properly.
2. Using reduce() Method with split()
You can manually parse the query string by splitting it into key-value pairs and then using the reduce() method to construct the object. This method allows for greater flexibility in handling custom conversions for null, undefined, and boolean values.
JavaScript
function strToObj(query) {
return query
.substring(1) // Remove the leading '?'
.split("&") // Split into key-value pairs
.reduce((acc, pair) => {
const [key, value] = pair.split("=");
acc[key] = value === "null"
? null
: value === "undefined"
? undefined
: value === "true"
? true
: value === "false"
? false
: value;
return acc;
}, {});
}
const query = "?name=Rahul&age=30&isAdmin=true&city=null";
const res = strToObj(query);
console.log(res);
Output{ name: 'Rahul', age: '30', isAdmin: true, city: null }
- .substring(1) removes the leading question mark ? from the query string.
- .split('&') breaks the query string into individual key-value pairs.
- reduce() constructs the final object by checking each value and converting it to the appropriate type (e.g., null, undefined, true, false).
3. Using decodeURIComponent() for Decoding Special Characters
In some cases, query string values might be URL-encoded, and you may need to decode these values before parsing. Using decodeURIComponent() helps handle special characters like spaces and special symbols.
JavaScript
function strToObj(q) {
const obj = {};
const pairs = q.substring(1).split("&");
pairs.forEach((pair) => {
const [key, value] = pair.split("=");
obj[decodeURIComponent(key)] = decodeURIComponent(value) === "null"
? null
: decodeURIComponent(value) === "undefined"
? undefined
: value === "true"
? true
: value === "false"
? false
: decodeURIComponent(value);
});
return obj;
}
const q = "?name=Amit&age=30&isAdmin=true&city=null&address=New%20Delhi";
const res = strToObj(q);
console.log(res);
Output{
name: 'Amit',
age: '30',
isAdmin: true,
city: null,
address: 'New Delhi'
}
- decodeURIComponent() decodes URL-encoded characters, ensuring that special characters in the query string (e.g., spaces as %20) are correctly handled.
- The rest of the logic is similar to the previous method but now includes decoding for both keys and values.
4. Using Regular Expressions for Query String Parsing
Regular expressions provide a powerful way to extract key-value pairs from a query string. You can use them to parse and convert values into the appropriate data types (e.g., null, undefined, true, false).
JavaScript
function strToObj(q) {
const regex = /[?&]([^=]+)=([^&]*)/g;
let match;
const obj = {};
while ((match = regex.exec(q)) !== null) {
const key = decodeURIComponent(match[1]);
let val = decodeURIComponent(match[2]);
obj[key] = val === "null"
? null
: val === "undefined"
? undefined
: val === "true"
? true
: val === "false"
? false
: val;
}
return obj;
}
const q = "?name=Amit&age=30&isAdmin=true&city=null";
const res = strToObj(q);
console.log(res);
Output{ name: 'Amit', age: '30', isAdmin: true, city: null }
- The regular expression /[?&]([^=]+)=([^&]*)/g matches all key-value pairs in the query string.
- decodeURIComponent() ensures that encoded characters are decoded correctly.
- The rest of the logic checks for special values like null, undefined, and booleans.
Which Approach to Choose?
Method | When to Use | Why Choose It |
---|
URLSearchParams API | When working with modern browsers and simple query string parsing. | Easy to use, built-in method, and handles query string parsing natively. |
reduce() with split() | When you need a custom parsing method or want to handle more complex scenarios. | Provides flexibility to handle special cases and custom parsing logic. |
decodeURIComponent() | When dealing with URL-encoded query strings. | Ensures special characters in query strings are properly decoded. |
Regular Expressions | When you need more control over the parsing process. | Powerful for complex or non-standard query string formats. |