JavaScript:解析字符串布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5219105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Parsing a string Boolean value?
提问by AgileMeansDoAsLittleAsPossible
JavaScript has parseInt()
and parseFloat()
, but there's no parseBool
or parseBoolean
method in the global scope, as far as I'm aware.
JavaScript 有parseInt()
and parseFloat()
,但据我所知,全局范围内没有parseBool
orparseBoolean
方法。
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean
.
我需要一个方法,它接受带有“true”或“false”等值的字符串并返回一个 JavaScript Boolean
。
Here's my implementation:
这是我的实现:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
这是一个很好的功能吗?请给我您的反馈。
Thanks!
谢谢!
回答by RGB
I would be inclined to do a one liner with a ternary if.
我倾向于用三元 if 做一个单衬。
var bool_value = value == "true" ? true : false
Edit:Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
编辑:甚至更快的是避免使用逻辑语句,而只使用表达式本身:
var bool_value = value == 'true';
This works because value == 'true'
is evaluated based on whether the value
variable is a string of 'true'
. If it is, that whole expression becomes true
and if not, it becomes false
, then that result gets assigned to bool_value
after evaluation.
这是有效的,因为它value == 'true'
是根据value
变量是否为'true'
. 如果是,则整个表达式变为true
,如果不是,则变为false
,则bool_value
在评估后将该结果分配给。
回答by F.Alves
You can use JSON.parse for that:
您可以为此使用 JSON.parse:
JSON.parse("true"); //returns boolean true
回答by Martin Jespersen
It depends how you wish the function to work.
这取决于您希望该功能如何工作。
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
如果您只想测试字符串中的“true”一词,并将没有它的任何字符串(或非字符串)定义为 false,那么最简单的方法可能是:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
如果您想确保整个字符串都是 true,您可以这样做:
function parseBoolean(str) {
return /^true$/i.test(str);
}
回答by Paul Fleming
You can try the following:
您可以尝试以下操作:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
如果它是一个有效值,则返回等效的 bool 值,否则返回 null。
回答by RoToRa
Personally I think it's not good, that your function "hides" invalid values as false
and - depending on your use cases - doesn't return true
for "1"
.
我个人认为这是不好的,你的函数“隐藏”无效值false
和-根据您的使用情况-不返回true
的"1"
。
Another problem could be that it barfs on anything that's not a string.
另一个问题可能是它对任何不是字符串的东西产生呕吐。
I would use something like this:
我会使用这样的东西:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0"
and "1"
.
并根据用例扩展它以区分"0"
和"1"
。
(Maybe there is a way to compare only once against "true"
, but I couldn't think of something right now.)
(也许有一种方法可以只与 比较一次"true"
,但我现在想不出什么。)
回答by rsp
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
您可以使用 JSON.parse 或 jQuery.parseJSON 并使用以下内容查看它是否返回 true:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
回答by CodeGems
You can add this code:
您可以添加以下代码:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
像这样工作:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
回答by Stefan Steiger
Wood-eye be careful. After looking at all this code, I feel obligated to post:
木眼小心。看完所有这些代码后,我觉得有必要发布:
Let's start with the shortest, but very strict way:
让我们从最短但非常严格的方式开始:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
并以适当的、更宽容的方式结束:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
if(str === true)
return true;
return false;
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
测试:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
回答by MiniGod
Why not keep it simple?
为什么不保持简单?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
回答by jwaliszko
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParsein C#, which supports out
params. In JavaScript it can be implemented in the following manner:
我喜欢 RoToRa 提供的解决方案(尝试解析给定的值,如果它有任何布尔含义,否则 - 不要)。不过我想提供一些小的修改,让它或多或少地像C# 中的Boolean.TryParse一样工作,它支持out
参数。在 JavaScript 中,它可以通过以下方式实现:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
用法:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);