Boolean or not ?
SOLVED- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-21-2021
02:39 PM
01-21-2021
02:39 PM
Boolean or not ?
We have the need to set/get boolean value on components where sometimes property, or test data is not a boolean.
Please share and discuss about your best way to determine if a value is a boolean.
Mine is below.
/**
* <a id="stringToBoolean"></a>
* Renvoie le type boolean true ou false selon la chaîne en entrée :<br>
* - "true", "yes", "on", "1", "oui", "vrai", "checked" renvoie true<br>
* - "false", "no", "off", "0", "non", "faux", "unchecked", "", null renvoie false<br>
* - autres valeurs, essaye de convertir en String pour l'évaluer, le cas échéant renvoie false
* @function
* {string} [value=""] - Chaîne à convertir
* @returns {boolean} Renvoie <b>true</b> ou <b>false</b>
*/
function stringToBoolean (value = "") {
if (typeof value != 'string') {
try {
value = value.toString();
}
catch(e) {
value = "";
}
}
switch(value.toLowerCase().trim()){
case "true" :
case "yes" :
case "on" :
case "1" :
case "oui" :
case "vrai" :
case "checked" :
return true;
case "false" :
case "no" :
case "0" :
case "off" :
case "" :
case "non" :
case "faux" :
case "unchecked" :
case null :
return false;
default:
return Boolean(value);
}
}
Un sourire et ça repart
Solved! Go to Solution.
10 REPLIES 10
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-14-2021
11:01 PM
02-14-2021
11:01 PM
@BenoitB wrote:We have the need to set/get boolean value on components where sometimes property, or test data is not a boolean.
Please share and discuss about your best way to determine if a value is a boolean.
Mine is below.
/**
* <a id="stringToBoolean"></a>
* Renvoie le type boolean true ou false selon la chaîne en entrée :<br>
* - "true", "yes", "on", "1", "oui", "vrai", "checked" renvoie true<br>
* - "false", "no", "off", "0", "non", "faux", "unchecked", "", null renvoie false<br>
* - autres valeurs, essaye de convertir en String pour l'évaluer, le cas échéant renvoie false
* @function
* {string} [value=""] - Chaîne à convertir
* @returns {boolean} Renvoie <b>true</b> ou <b>false</b>
*/
function stringToBoolean (value = "") {
if (typeof value != 'string') {
try {
value = value.toString();
}
catch(e) {
value = "";
}
}
switch(value.toLowerCase().trim()){
case "true" :
case "yes" :
case "on" :
case "1" :
case "oui" :
case "vrai" :
case "checked" :
return true;
case "false" :
case "no" :
case "0" :
case "off" :
case "" :
case "non" :
case "faux" :
case "unchecked" :
case null :
return false;
default:
return Boolean(value);
}
}
Thanks for the support

- « Previous
-
- 1
- 2
- Next »
- « Previous
-
- 1
- 2
- Next »