Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Boolean in javascript [duplicate]

Tags:

javascript

How to convert a string to Boolean ?

I tried using the constructor Boolean("false"), but it's always true.

like image 411
user137348 Avatar asked Dec 03 '10 10:12

user137348


People also ask

Can you convert string to boolean?

To convert String to boolean in Java, you can use Boolean. parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean. valueOf(string) method.

How do you convert string false to boolean false?

The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true'); For a more case insensitive approach, try: let myBool = (myString.

What is the correct operation to convert string to boolean value in JavaScript?

One of the easiest ways to convert the string to the boolean is to use the comparison ('==') operator with the ternary (? :) operator. However, users can use only the comparison operator also.

How do you do boolean with strings?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".


2 Answers

I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).

var myBool = myString == "true"; 
like image 116
Aistina Avatar answered Sep 22 '22 07:09

Aistina


I would like to answer this to improve upon the accepted answer.

To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.

function stringToBool(val) {     return (val + '').toLowerCase() === 'true'; } 

JSPerf

enter image description here

like image 21
Jeff Voss Avatar answered Sep 25 '22 07:09

Jeff Voss