如何在JavaScript中将字符串转换为布尔值?

JavaScript

老丝村村Stafan

2020-03-09

我可以将表示布尔值(例如,“ true”,“ false”)的字符串转换为JavaScript中的固有类型吗?

我有一个隐藏的HTML表单,可根据用户在列表中的选择进行更新。此表单包含一些表示布尔值的字段,并使用内部布尔值动态填充。但是,一旦将此值放入隐藏的输入字段中,它将成为一个字符串。

确定字段的布尔值(将其转换为字符串后)的唯一方法是依赖于其字符串表示形式的文字值。

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

有没有更好的方法可以做到这一点?

第181篇《如何在JavaScript中将字符串转换为布尔值?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
飞云前端西门 2020.03.09

Holy god some of these answers are just wild. I love JS and its infinite number of ways to skin a bool.

My preference, which I was shocked not to see already, is:

testVar = testVar.toString().match(/^(true|[1-9][0-9]*|[0-9]*[1-9]+|yes)$/i) ? true : false;
LEYJim 2020.03.09

My take on this question is that it aims to satisfy three objectives:

  • Return true/false for truthy and falsey values, but also return true/false for multiple string values that would be truthy or falsey if they were Booleans instead of strings.
  • Second, provide a resilient interface so that values other than those specified will not fail, but rather return a default value
  • Third, do all this with as little code as possible.

The problem with using JSON is that it fails by causing a Javascript error. This solution is not resilient (though it satisfies 1 and 3):

JSON.parse("FALSE") // fails

This solution is not concise enough:

if(value === "TRUE" || value === "yes" || ...) { return true; }

I am working on solving this exact problem for Typecast.js. And the best solution to all three objectives is this one:

return /^true$/i.test(v);

It works for many cases, does not fail when values like {} are passed in, and is very concise. Also it returns false as the default value rather than undefined or throwing an Error, which is more useful in loosely-typed Javascript development. Bravo to the other answers that suggested it!

JinJin猴子 2020.03.09

To convert both string("true", "false") and boolean to boolean

('' + flag) === "true"

Where flag can be

 var flag = true
 var flag = "true"
 var flag = false
 var flag = "false"
SamStafan十三 2020.03.09
Boolean.parse = function (str) {
  switch (str.toLowerCase ()) {
    case "true":
      return true;
    case "false":
      return false;
    default:
      throw new Error ("Boolean.parse: Cannot convert string to boolean.");
  }
};
ItachiHarry 2020.03.09

I use the following:

function parseBool(b) {
    return !(/^(false|0)$/i).test(b) && !!b;
}

This function performs the usual Boolean coercion with the exception of the strings "false" (case insensitive) and "0".

LEYEvaL 2020.03.09

Universal solution with JSON parse:

function getBool(val) {
    return !!JSON.parse(String(val).toLowerCase());
}

getBool("1"); //true
getBool("0"); //false
getBool("true"); //true
getBool("false"); //false
getBool("TRUE"); //true
getBool("FALSE"); //false

UPDATE (without JSON):

function getBool(val){ 
    var num = +val;
    return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');
}

I also created fiddle to test it http://jsfiddle.net/remunda/2GRhG/

GO神奇 2020.03.09
stringToBoolean: function(string){
    switch(string.toLowerCase().trim()){
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
}
十三村村蛋蛋 2020.03.09

我认为这很普遍:

if (String(a) == "true") ...

它去了:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false
十三西里GO 2020.03.09

警告

从技术上来说,这个极受推崇的旧式答案是正确的,但仅适用于特定情况,即您的字符串值为EXACTLY "true""false"

在下面的函数中传递的无效json字符串将引发异常


原始答案:

怎么样?

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

或与jQuery

$.parseJSON("TRUE".toLowerCase());

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android