简体   繁体   中英

Javascript check if string if true or false and convert to Boolean

Is there a better way to improve the below statement to check if the val() is 'true' or 'false' and if it is then it will change it to a Boolean. The reason being, some of the values may be a word.

var thisval = $(this).val();
if (thisval == "true"){
    ao[id] = true;
} else if (thisval == "false"){
    ao[id] = false;
} else {
    ao[id] = $(this).val();
}

Most readable:

var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : 
         thisval === 'false' ? false : 
         thisval;

One-liner based on the conditional operator:

var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : (thisval === 'false' ? false : thisval);

One-liner based on ||and && behavior:

var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval !== 'false') && thisval || false;

Shortest one-liner (combination of the above):

var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval === 'false' ? false : thisval);

Try JSON.parse() .

"true" and "false" are actually json representations of true , false . This is how ajax parses json object as a string from server side. If on server side, we return true, false => the browser will receive it as a string "true" or "false" (json representation)

if ( $(this).val() == "true" ||  $(this).val() == "false") {
    ao[id] = JSON.parse($(this).val());
}else {
    ao[id] = $(this).val();
}

DEMO

String.prototype.bool = function() {
    return (/^true$/i).test(this);
};


if ( $(this).val() == "true" ||  $(this).val() == "false") {
    ao[id] = $(this).val().bool();
}else {
    ao[id] = $(this).val();
}

This might be slightly more elegant:

var thisval = $(this).val();

if (thisval === "true" || thisval === "false") {
    thisval = (thisval === "true");
}
('' + thisval).toLowerCase() === 'true'

May be useful if extra string and toLower is negligible - may be simple.

Its true if its explicitly set to true, (boolean or case insensitive string) and false otherwise.

 // so complete solution to get the same value if neither true nor false
const thisvalStr = ('' + thisval).toLowerCase();
a[id] = thisvalStr === 'true'? true: (thisvalStr === 'false')? false: thisval;

Can be modified to include additional values like, 1, etc as per need by using ||or an array.

const TrueValuesStr = ['1', 'true']

TrueValueStr.contains(('' + thisval).toLowerCase() === 'true')
var thisval = $(this).val();

switch(thisval) { 
case 'true' : 
    ao[id] = true; 
    break; 

case 'false' : 
    ao[id] = false; 
    break; 

default: 
    ao[id] = thisval; 

}

I would create an array to hold the two possible values for when the string is true or false. Then, I would search to see if thisval is found inside that array. If it is not, the indexOf function will return -1. Afterwards, it is just a matter of going over those values and build up the cases that you want.

EDIT : I have updated the code based on the suggestion of Tibos. Thank you!

I'd prob prefer

const parseMaybeBool = val =>
  typeof val === 'string'
    ? val.toLowerCase() === 'true' || val.toLowerCase() === 'false'
      ? Boolean(val)
      : val
    : val;

or w/ types

const isBool = (val: unknown): val is boolean =>
  typeof val === 'boolean' ||
  (typeof val === 'string' &&
    (val.toLowerCase() === 'true' || val.toLowerCase() === 'false'));

const parseMaybeBool = (val: unknown) =>
  isBool(val) ? Boolean(val) : val;

In the pleasant summer of 2022, here's how I'd do it:

const thisval = $(this).val();

ao[id] = ['true', 'false'].includes(thisval) ? JSON.parse(thisval) : thisval;

You could also go a step further and have it handle numbers too:

ao[id] = ['true', 'false'].includes(thisval) || !Number.isNaN(Number(thisval))
  ? JSON.parse(thisval)
  : thisval;

You can do all of this in one line if you want to:

const getBool = value => value == "true" || value == "false" ? value == "true" : value;

getBool($(this).val());

Explanation

In JavaScript you'll probably be used to using something like

if(answer == "yes"){ ...

answer == "yes" will evaluate to true or false .

For your question, this can certainly help one part of it. If there were only "true" or "false" options it would be as simple as:

const getBool = (value) => value == "true"
getBool("true"); // true
getBool("false"); // false

We can now wrap this in a ternary operator, basic overview:

`if this` ? `then do this` : `if not, then do this`

So we check if the value is true or false, and if so use the above technique.

value == "true" || value == "false" 

If its not, we can just return the value without any modifications. So the test becomes:

value == "true" || value == "false" ? value == "true" : value;

In nodejs by using node-boolify we can use isBoolean() & Boolify()

Validation Results

var isBoolean = require('node-boolify').isBoolean;

isBoolean(true); //true
isBoolean('true'); //true
isBoolean('TRUE'); //false
isBoolean(1); //true
isBoolean(2); //false
isBoolean(false); //true
isBoolean('false'); //true
isBoolean('FALSE'); //false
isBoolean(0); //true
isBoolean(null); //false
isBoolean(undefined); //false
isBoolean(); //false
isBoolean(''); //false

Boolean Conversion Results

var Boolify = require('node-boolify').Boolify;

Boolify(true); //true
Boolify('true'); //true
Boolify('TRUE'); //null
Boolify(1); //true
Boolify(2); //null
Boolify(false); //false
Boolify('false'); //false
Boolify('FALSE'); //null
Boolify(0); //false
Boolify(null); //null
Boolify(undefined); //null
Boolify(); //null
Boolify(''); //null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM