JavaScript - Convert a String to Boolean in JS
Last Updated :
17 Nov, 2024
Here are different ways to convert string to boolean in JavaScript.
1. Using JavaScript == Operator
The == operator compares the equality of two operands. If equal then the condition is true otherwise false.
Syntax
console.log(YOUR_STRING == 'true');
JavaScript
let str1 = "false";
console.log(str1 == 'true');
let str2 = "True";
console.log(str2.toLowerCase() == 'true');
2. Using JavaScript === Operator
This operator compares the equality of two operands with type. If equal(type and value both) then the condition is true otherwise false. It strictly checks the condition.
Note: As the operator strictly checks the condition, so if you do not use toLowerCase(), then it will give you the "false" as a Boolean value.
JavaScript
let str = "true";
console.log(str === 'true');
str = "True";
console.log(str.toLowerCase() === 'true');
3. Using Boolean() Function
The boolean function returns the boolean value of the variable. It can also be used to find the boolean result of a condition, expression, etc. The Boolean() function evaluates the input and returns a boolean value. In this case, since the input string "true" is non-empty, the Boolean() function returns true.
JavaScript
let str = "true";
let result = Boolean(str);
console.log(result);
4. Using a Regular Expression
We can use regular expression to convert a string to a Boolean value in JavaScript.
The regular expression /^true$/i is used with the test() method to check if the string matches the pattern "true" (case-insensitive). The ^ symbol denotes the start of the string, $ denotes the end of the string, and the i flag makes the pattern case-insensitive.
JavaScript
let str = "true";
let boolValue = /^true$/i.test(str);
console.log(boolValue);
5. Using !! (Double Negation) Operator
The !! (double negation) operator is a commonly used approach to convert a string to a boolean value in JavaScript. The first negation (!) converts the string into its opposite boolean value, and the second negation (!) reverts it back to the original boolean value. that helps us to change the given string to boolean value.
JavaScript
let str = "true";
let boolValue = !!str;
console.log(boolValue);
6. Using JSON.parse() Method
The JSON.parse() method can be used to convert a string to a boolean value in JavaScript. JSON.parse() method is used to parse the string "true" and convert it into its corresponding boolean value, which is true.
JavaScript
let str = "true";
let boolValue = JSON.parse(str);
console.log(boolValue);
7. Using Ternary Operator
The ternary operator can also be used to convert a string to a boolean, the code employs a concise one-liner. The toLowerCase()
method is applied to ensure case-insensitive comparison. The ternary operator checks if the lowercase string is equal to 'true'. If the condition is met, it returns true
; otherwise, it returns false
.
JavaScript
function stringToBooleanTernary(str) {
// Ternary operator: condition ? true-value : false-value
return str.toLowerCase() === 'true' ? true : false;
}
// Example usage
const resultTernary = stringToBooleanTernary('True');
console.log(resultTernary); // Output: true
8. Using Switch Case
The switch case approach involves using a switch
statement to evaluate the lowercase string. Cases are defined for 'true' and 'false', each returning the corresponding boolean value. The default
case is included to handle invalid input by throwing an error.
JavaScript
function stringToBooleanSwitch(str) {
switch (str.toLowerCase()) {
case 'true':
return true;
case 'false':
return false;
default:
throw new Error('Invalid boolean string');
}
}
// Driver code
try {
const resultSwitch = stringToBooleanSwitch('False');
console.log(resultSwitch); // Output: false
} catch (error) {
console.error(error.message);
}
Similar Reads
Convert a JavaScript Enum to a String Enums in JavaScript are used to represent a fixed set of named values. In JavaScript, Enumerations or Enums are used to represent a fixed set of named values. However, Enums are not native to JavaScript, so they are usually implemented using objects or frozen arrays. In this article, we are going to
2 min read
JavaScript - Convert String to Array Strings in JavaScript are immutable (cannot be changed directly). However, arrays are mutable, allowing you to perform operations such as adding, removing, or modifying elements. Converting a string to an array makes it easier to:Access individual characters or substrings.Perform array operations su
5 min read
How to convert Number to Boolean in JavaScript ? We convert a Number to Boolean by using the JavaScript Boolean() method and double NOT operator(!!). A JavaScript boolean results in one of two values i.e. true or false. However, if one wants to convert a variable that stores integer â0â or â1â into Boolean Value i.e. "false" or "true". Below are
2 min read
How to convert an object to string using JavaScript ? To convert an object to string using JavaScript we can use the available methods like string constructor, concatenation operator etc. Let's first create a JavaScript object. JavaScript // Input object let obj_to_str = { name: "GeeksForGeeks", city: "Noida", contact: 2488 }; Examp
4 min read
How to convert string to boolean in PHP? Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value. Examples: Input : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN); Output : true Input : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN); Output
2 min read
How to Generate a Random Boolean using JavaScript? To generate a random boolean in JavaScript, use Math.random(), which returns a random number between 0 and 1.Approach: Using Math.random() functionCalculate Math.random() function.If it is less than 0.5, then true otherwise false.Example 1: This example implements the above approach. JavaScript// Fu
1 min read
JavaScript Boolean toString() Method The boolean.toString() method is used to return a string either "true" or "false" depending upon the value of the specified boolean object. Syntax: boolean.toString() Parameter: This method does not accept any parameter. Return Values: It returns a string either "true" or "false" depending upon the
3 min read
How to toggle a boolean using JavaScript ? A boolean value can be toggled in JavaScript by using two approaches which are discussed below: Table of Content Using the logical NOT operatorUsing the ternary operatorUsing the XOR (^) operatorMethod 1: Using the logical NOT operator The logical NOT operator in Boolean algebra is used to negate an
3 min read
Convert Boolean Result into Number/Integer in JavaScript A JavaScript boolean represents one of two values: true or false. However, if one wants to convert a variable that stores a boolean value, into an integer "0" or "1", they can do so using multiple approaches. Below are the approaches to convert a boolean to a number/integer in JavaScript:Table of Co
3 min read
JavaScript - Converting Query String to Object with Null, Undefined, and Boolean Values Here are the different methods to convert query string to object with null, undefined and boolean values.1. Using URLSearchParams APIThe URLSearchParams interface provides an easy and modern way to work with query strings. It lets you easily parse the query string and convert it into a JavaScript ob
4 min read