admin管理员组文章数量:1125299
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?
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?
Share Improve this question edited Feb 29, 2024 at 21:29 community wiki3 revs, 3 users 64%
Kevin 18 | Show 13 more comments
110 Answers
Reset to default 1 2 3 4 Next 5041Do:
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());
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);
}
}
I think this is much more universal:
if (String(a).toLowerCase() == "true")
...
It goes:
String(true) == "true" //returns true
String(false) == "true" //returns false
String("true") == "true" //returns true
String("false") == "true" //returns false
Remember to match case:
var isTrueSet = (myValue.toLowerCase() === 'true');
Also, if it's a form element checkbox, you can also detect if the checkbox is checked:
var isTrueSet = document.myForm.IS_TRUE.checked;
Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.
This is the easiest way to do boolean conversion I came across recently. Thought of adding it.
JSON.parse('true');
let trueResponse = JSON.parse('true');
let falseResponse = JSON.parse('false');
console.log(trueResponse);
console.log(falseResponse);
You can use regular expressions:
/*
* Converts a string to a bool.
*
* This conversion will:
*
* - match 'true', 'on', or '1' as true.
* - ignore all white-space padding
* - ignore capitalization (case).
*
* ' tRue ','ON', and '1 ' will all evaluate as true.
*
*/
function strToBool(s)
{
// will match one and only one of the string 'true','1', or 'on' regardless
// of capitalization and regardless of surrounding white-space.
//
regex=/^\s*(true|1|on)\s*$/i
return regex.test(s);
}
If you like extending the String class you can do:
String.prototype.bool = function() {
return strToBool(this);
};
alert("true".bool());
For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about clashing with other code that extends the String object:
Object.defineProperty(String.prototype, "com_example_bool", {
get : function() {
return (/^(true|1)$/i).test(this);
}
});
alert("true".com_example_bool);
(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)
Wood-eye be careful. After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:
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, strict)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if (str == null)
{
if (strict)
throw new Error("Parameter 'str' is null or undefined.");
return false;
}
if (typeof str === 'boolean')
{
return (str === true);
}
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]));}
I thought that @Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:
function isTrue(value){
if (typeof(value) === 'string'){
value = value.trim().toLowerCase();
}
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
It's not necessary to cover all the false
cases if you already know all of the true
cases you'd have to account for. You can pass anything into this method that could pass for a true
value (or add others, it's pretty straightforward), and everything else would be considered false
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/
Your solution is fine.
Using ===
would just be silly in this case, as the field's value
will always be a String
.
The Boolean object doesn't have a 'parse' method. Boolean('false')
returns true, so that won't work. !!'false'
also returns true
, so that won't work also.
If you want string 'true'
to return boolean true
and string 'false'
to return boolean false
, then the simplest solution is to use eval()
. eval('true')
returns true and eval('false')
returns false.
Keep in mind the performance and security implications when using eval()
though.
var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) {
return !falsy.test(val) && !!val;
};
This returns false
for every falsy value and true
for every truthy value except for 'false'
, 'f'
, 'no'
, 'n'
, and '0'
(case-insensitive).
// False
Boolean.parse(false);
Boolean.parse('false');
Boolean.parse('False');
Boolean.parse('FALSE');
Boolean.parse('f');
Boolean.parse('F');
Boolean.parse('no');
Boolean.parse('No');
Boolean.parse('NO');
Boolean.parse('n');
Boolean.parse('N');
Boolean.parse('0');
Boolean.parse('');
Boolean.parse(0);
Boolean.parse(null);
Boolean.parse(undefined);
Boolean.parse(NaN);
Boolean.parse();
//True
Boolean.parse(true);
Boolean.parse('true');
Boolean.parse('True');
Boolean.parse('t');
Boolean.parse('yes');
Boolean.parse('YES');
Boolean.parse('y');
Boolean.parse('1');
Boolean.parse('foo');
Boolean.parse({});
Boolean.parse(1);
Boolean.parse(-1);
Boolean.parse(new Date());
There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create this jsPerf that I hope can throw some light here.
Brief of results (the higher the better):
- Conditional statement: 2,826,922
- Switch case on Bool object: 2,825,469
- Casting to JSON: 1,867,774
- !! conversions: 805,322
- Prototype of String: 713,637
They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.
This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive
var isTrueSet = (myValue.toLowerCase() === 'true');
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".
Simplest solution
本文标签: How can I convert a string to boolean in JavaScriptStack Overflow
版权声明:本文标题:How can I convert a string to boolean in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736659465a1946343.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
string=(string==String(string?true:false))?(string?true:false):(!string?true:false);
– Mark K Cowan Commented Apr 16, 2015 at 10:25function parseBool(val) { return val === true || val === "true" }
– WickyNilliams Commented Sep 10, 2015 at 14:24function checkBool(x) { if(x) {return true;} else {return false;} }
– Sebi Commented Nov 29, 2016 at 15:10if (checkBool(x) != false) { ... } else { ... }
– Mark K Cowan Commented Nov 29, 2016 at 18:21!!(parseInt(value) || value === "true")
– Andrei L Commented Feb 22, 2017 at 3:58