25

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.

3
  • 12
    You're doing everything right. Commented Sep 20, 2016 at 16:23
  • wouldn't Boolean(req.query.isUpdated) work? Commented Nov 26, 2021 at 15:47
  • 3
    @Vaulstein No, because Boolean("false") will evaluate to true. It is, after all, a valid string ; ) Commented Mar 7, 2022 at 21:04

10 Answers 10

8

Docs if you are using query-string

const queryString = require('query-string');

queryString.parse('foo=true', {parseBooleans: true});
//=> {foo: true}
Sign up to request clarification or add additional context in comments.

Comments

5

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)

Comments

4

I use this pair of lines:

let test = (value).toString().trim().toLowerCase(); let result = !((test === 'false') || (test === '0') || (test === ''));

Comments

3

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.

1 Comment

What would the variation be to leave isTrue undefined for null or undefined strings?
1
var myBoolean = (req.query.myParam === undefined || req.query.myParam.toLowerCase() === 'false' ? false : true)

1 Comment

if myParam is missing myParam.toLowerCase() will fail
1

My one-liner snippet:

const isTruthy = (val) => val && !['false', '0', ''].includes(val.toString().trim().toLowerCase());

Comments

1

Use JSON.parse for checking the boolean value in query params like this:

var isUpdated = JSON.parse(req.query.isUpdated)?true: false;

Comments

0

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;
            }
          }
})

Comments

0

With some ideas from previous answers, I ended up using this function to consider undefined values as well

const parseBool = (params) => {
 return !(
   params === "false" ||
   params === "0" ||
   params === "" ||
   params === undefined
 );
};

2 Comments

bit weird that parseBool(undefined) is false and parseBool(null) is true
yea likely because didn't check for null, hence negating the value
0

I created a package called boolean-query-express

https://www.npmjs.com/package/booleanize-query-express

The difference between it and the other packages is that it treats values as 1 and 0 as booleans and will consider params like isHere, isValid, hasSomething (camelcased).

You can read more about it as it's documented.

1 Comment

It shows 404 now. FYI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.