Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Parsing a string Boolean value? [duplicate]

Tags:

javascript

JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.

I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.

Here's my implementation:

function parseBool(value) {     return (typeof value === "undefined") ?             false :             // trim using jQuery.trim()'s source             value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true"; } 

Is this a good function? Please give me your feedback.

Thanks!

like image 963
AgileMeansDoAsLittleAsPossible Avatar asked Mar 07 '11 11:03

AgileMeansDoAsLittleAsPossible


People also ask

How do you pass a Boolean value to a string?

toString(boolean b): This method works same as String. valueOf() method. It belongs to the Boolean class and converts the specified boolean to String. If the passes boolean value is true then the returned string would be having “true” value, similarly for false the returned string would be having “false” value.

How do you convert 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.

Is boolean pass by reference JavaScript?

Primitive data types in Javascript like Number, String, Boolean always pass by value whereas Objects are pass by reference.


1 Answers

I would be inclined to do a one liner with a ternary if.

var bool_value = value == "true" ? true : false 

Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:

var bool_value = value == 'true'; 

This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.

like image 80
raddrick Avatar answered Oct 13 '22 01:10

raddrick