How to convert string to boolean in typescript Angular 4
I have been trying different values with JSON.parse(value)
and it seems to do the work:
// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));
// false
Boolean(JSON.parse("0"));
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));
Method 1 :
var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true
Method 2 :
var stringValue = "true";
var boolValue = (stringValue =="true"); //returns true
Method 3 :
var stringValue = "true";
var boolValue = JSON.parse(stringValue); //returns true
Method 4 :
var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true
Method 5 :
var stringValue = "true";
var 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;
}
}
source: http://codippa.com/how-to-convert-string-to-boolean-javascript/
In your scenario, converting a string to a boolean can be done via something like someString === 'true'
(as was already answered).
However, let me try to address your main issue: dealing with the local storage.
The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.
A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.
The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.
function setItemInStorage(key, item) {
localStorage.setItem(key, JSON.stringify(item));
}
function getItemFromStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
Your example could then be rewritten as:
setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);
And:
const pageLoadParams = getItemFromStorage('CheckOutPageReload');
if (pageLoadParams) {
this.btnLoginNumOne = pageLoadParams[0];
this.btnLoginEdit = pageLoadParams[1];
}
Define extension: String+Extension.ts
interface String {
toBoolean(): boolean
}
String.prototype.toBoolean = function (): boolean {
switch (this) {
case 'true':
case '1':
case 'on':
case 'yes':
return true
default:
return false
}
}
And import in any file where you want to use it '@/path/to/String+Extension'