How can I convert a string to boolean in JavaScript?

3.6k2008 年提問 · Kevin ·javascriptboolean-expressionboolean-operationsstring-conversion 主題:型別、比較與數字 → 在 Stack Overflow 看原文 ↗

Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based on a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?

重點答案

5.1k採納 by guinaps 原文 ↗

Do:

var isTrueSet = (myValue === 'true');

Use the strict equality operator (===), which doesn't make any implicit type conversions when the compared variables have different types.

This will set isTrueSet to a boolean true if the string is "true" and boolean false if it is string "false" or not set at all.

For making it case-insensitive, try:

var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === 'true');

Don't:

You should be cautious about using these two methods for your specific needs.

var myBool = Boolean("false"); // evaluates to true
var myBool = !!"false"; // evaluates to true

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

Warning

This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false".

An invalid json string passed into these functions below WILL throw an exception.


Original answer:

How about?

JSON.parse("True".toLowerCase());

or with jQuery

$.parseJSON("TRUE".toLowerCase());
301 by Steven 原文 ↗
const stringToBoolean = (stringValue) => {
    switch(stringValue?.toLowerCase()?.trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

        case "false": 
        case "no": 
        case "0": 
        case null: 
        case undefined:
          return false;

        default: 
          return JSON.parse(stringValue);
    }
}