Proper way to parse Boolean query string param in node/express
Solution 1
Docs if you are using query-string
const queryString = require('query-string');
queryString.parse('foo=true', {parseBooleans: true});
//=> {foo: true}
Solution 2
I use this pair of lines:
let test = (value).toString().trim().toLowerCase();
let result = !((test === 'false') || (test === '0') || (test === ''));
Solution 3
The only thing I would change about your approach is to make it case insensitive:
var isUpdated = ((req.query.isUpdated+'').toLowerCase() === 'true')
You could make this a utility function as well if you like:
function queryParamToBool(value) {
return ((value+'').toLowerCase() === 'true')
}
var isUpdated = queryParamToBool(req.query.isUpdated)
Solution 4
Here is my generic solution for getting a query params as a boolean:
const isTrue = Boolean((req.query.myParam || "").replace(/\s*(false|null|undefined|0)\s*/i, ""))
It converts the query param into a string which is
then cleaned by suppressing any falsy string.
Any resulting non-empty string will be true
.
Solution 5
You can use qs package
A little code to parse int and booleans
qs.parse(request.querystring, {
decoder(str, decoder, charset) {
const strWithoutPlus = str.replace(/\+/g, ' ');
if (charset === 'iso-8859-1') {
// unescape never throws, no try...catch needed:
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
}
if (/^(\d+|\d*\.\d+)$/.test(str)) {
return parseFloat(str)
}
const keywords = {
true: true,
false: false,
null: null,
undefined,
}
if (str in keywords) {
return keywords[str]
}
// utf-8
try {
return decodeURIComponent(strWithoutPlus);
} catch (e) {
return strWithoutPlus;
}
}
})
Jesus_Maria
Updated on January 18, 2021Comments
-
Jesus_Maria over 3 years
I'm waiting for something like the following from the front end
....?isUpdated=true
so I did something like this in code (as I'm processing only
isUpdated=true
, false need to be ignored)var isUpdated = (req.query.isUpdated === 'true')
but it seems bit odd to me.
How to do this in proper way? I mean to parse a Boolean parameter from the query string.