Asked : Nov 17
Viewed : 25 times
Can I convert a javascript string representing a javascript boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent javascript 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 javascript string.
The only way I could find to determine the field's javascript boolean value, once it was converted into a javascript string, was to depend upon the literal value of its javascript string representation.
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
Is there a better way to accomplish this?
Nov 17
var isTrueSet = (myValue === 'true');
using the identity operator (===
), which doesn't make any implicit type conversions when the compared variables have different types.
You should probably be cautious about using these two methods for your specific needs:
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
Any string which isn't an empty string will evaluate to true
by using them. Although they're the cleanest methods I can think of concerning javascript boolean conversion, I think they're not what you're looking for.
answered Jan 17
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.
answered Jan 17
Using test()
let stringValue = "true";
let boolValue = (/true/i).test(stringValue) //returns true
test()
method of javascript matches a regular expression against a string.
In this case we check whether the string contains true or not. Now, if the string value is ‘true’, then boolValue will be true
, else a false
./i
at the end of regular expression is for case insensitive match.
answered Jan 17
Using switch-case
A switch-case construct is used to cover all possible string value combinations which should lead to a true
boolean value.
These string values may be ‘true’, ‘1’, ‘on’, ‘yes’. It also covers boolean true
or numeric 1.
If the given string (‘true’) or any other values match, then the boolean true
is returned while boolean false
is returned in every other case.
let stringValue = "true";
let boolValue = getBoolean(stringValue); //returns true
function getBoolean(value){
switch(value) {
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
answered Jan 17