How to Convert String to Boolean in JavaScript

To convert a string to a boolean in JavaScript, you can use the “== operator”“JSON.parse()”, or “custom” function.

Method 1: Using the “== operator”

You can compare the string with a specific boolean value as a string, such as ‘true’ or ‘false’. This method is case-sensitive and only works for these exact string representations.

Example

const str = 'true';
const boolValue = str === 'true';

console.log(boolValue)
console.log(typeof(boolValue))

Output

true
boolean

Method 2: Using the JSON.parse() function

The JSON.parse() is used to parse a JSON string and convert it into a JavaScript object. If the input string is ‘true’ or ‘false’, it will be converted to a boolean value. However, this method will throw an error if the input string is not valid JSON.

Example

let data = "Millie Bobby Brown"

let data_bool = Boolean(data)

console.log(typeof(data_bool))
console.log(data_bool)

Output

boolean
true

Method 3: Using a custom function

You can create a custom function to handle the conversion based on your specific requirements. This method allows for more flexibility and control over the conversion process.

function stringToBoolean(str) {
  const trimmedString = str.trim().toLowerCase();
  return trimmedString === 'true' || trimmedString === '1';
}

const str = 'true';
const boolValue = stringToBoolean(str);

const str2 = 'false';
const boolValue2 = stringToBoolean(str2);

console.log(boolValue)
console.log(boolValue2)

Output

true
false

In this custom function, the input string is first trimmed and converted to lowercase to handle different casing scenarios. Then, it checks if the lowercase string equals ‘true’ or ‘1’ and returns true if either condition is met. Otherwise, it returns false.

Each of these methods has its advantages and limitations.

The comparison method is simple and efficient but only works for specific string values.

JSON.parse() is more flexible but can throw errors for invalid JSON input.

The custom function provides the most control over the conversion process and can handle a wider range of input scenarios.

Use the appropriate method as per your requirements.

Leave a Comment