Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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();
}
like image 596
ngplayground Avatar asked Nov 11 '13 13:11

ngplayground


People also ask

How do you check if a string is true or false?

parseBoolean(String s) − This method accepts a String variable and returns boolean. If the given string value is "true" (irrespective of its case) this method returns true else, if it is null or, false or, any other value it returns false.

How do I cast a string to a boolean in TypeScript?

To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned.

Under which conditions does boolean convert a string to true?

The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string " true ".


3 Answers

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();
}
like image 72
Ankit Tyagi Avatar answered Oct 02 '22 20:10

Ankit Tyagi


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);
like image 22
Tibos Avatar answered Oct 19 '22 05:10

Tibos


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

like image 10
Khanh TO Avatar answered Oct 19 '22 04:10

Khanh TO