142

I know am not the first to ask this and as I mentioned in my title ,I am trying to convert string value boolean .

I have previously put some values into local storage,Now I want to get all the values and assign all to the some boolean variables .

app.component.ts

localStorage.setItem('CheckOutPageReload', this.btnLoginNumOne + ',' + this.btnLoginEdit);

here this.btnLoginNumOne and this.btnLoginEdit are string values ("true,false").

mirror.component.ts

if (localStorage.getItem('CheckOutPageReload')) {
      let stringToSplit = localStorage.getItem('CheckOutPageReload');
      this.pageLoadParams = stringToSplit.split(',');

      this.btnLoginNumOne = this.pageLoadParams[0]; //here I got the error as boolean value is not assignable to string
      this.btnLoginEdit = this.pageLoadParams[1]; //here I got the error as boolean value is not assignable to string
}

in this component this.btnLoginNumOne and this.btnLoginEdit are Boolean values;

I tried the solutions in stackoverflow but nothing is worked.

Can anyone help me to fix this .

Akj
  • 7,038
  • 3
  • 28
  • 40
Zhu
  • 3,679
  • 14
  • 45
  • 76
  • 4
    Possible duplicate of [How can I convert a string to boolean in JavaScript?](https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) – ConnorsFan Aug 25 '18 at 13:40

10 Answers10

279

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/

zs2020
  • 53,766
  • 29
  • 154
  • 219
Ayoub k
  • 7,788
  • 9
  • 34
  • 57
  • 6
    Method 5: looks too good. You can add cases for touppercase for 'ON', 'YES', 'TRUE' to ensure upper case test. – Inaam ur Rehman Dec 18 '18 at 10:20
  • 8
    consider using "===" – Karl Scholze Jan 10 '20 at 16:34
  • 1
    You can extend method 1's regex by other test values like (/(true|1)/i).test(myString) to check for _true_ or _1_ – Kay May 08 '20 at 08:48
  • I think I would combine method 3 & 4. I'm not sure about method 5 with "on" or "yes" returning boolean. A boolean shouldn't really be a string like that. – kahlan88 Sep 08 '20 at 08:57
  • Old and reliable =) I also like !!'true' (as old as JS) – Volodymyr Bilovus Jun 05 '21 at 13:38
  • JSON.parse(stringValue) will fail if input is null or undefined. – Yanal-Yves Fargialla Jan 02 '23 at 16:43
  • Can you maybe add an explanation to `(/true/i)`? Is the `i` meaning case insensitive regex? – Kellen Stuart Feb 16 '23 at 19:24
  • It's probably obvious, but just to have it said, only methods 1 and 4 are case-insensitive. All of the rest will return `false` if the string being tested is `"True"`. Method 1 returns `true` if "true" appears anywhere in the string. So it will return `true` if the string being tested is `"NotTrue"` (This can be fixed by changing the regex to `/^true$/i`). Method 3 will throw an exception if the value being tested can't be parsed as `true`, `false`, or `null`. `"True"`, `"foo"`, and `undefined` all result in an exception. – Elezar Jul 10 '23 at 23:59
  • Method 4 will throw an exception if the value being tested is null or undefined. It will also throw an exception if the value being tested isn't a string. For example, if the value is `true` (i.e., it's already a Boolean), then it will result in an exception. All of these except for method 3 will return false for any string value that's not "true" (or in the case of method 5, one of the specified values). That's probably fine in a lot of cases, but a better general solution would be to return null if the value being tested isn't a clear `true` or `false` value. – Elezar Jul 11 '23 at 00:09
57

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));
Gonzalo
  • 1,781
  • 15
  • 29
  • 9
    This has the potential to throw an exception if the input is not valid JSON (like `on` or `yes` for example). – Kyle Pittman Mar 13 '19 at 19:47
  • I had the same concern as Monkpit, but this was the only solution that I found to work when testing my application at runtime AND when unit testing. – KrimblKrum Nov 08 '21 at 22:10
  • To expand on what @KylePittman said, even values like `"True"` or `"FALSE"` where it's not all lower-case will throw an exception. If the value is undefined, it also throws an exception. – Elezar Jul 11 '23 at 00:13
10

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];
}
nunocastromartins
  • 577
  • 1
  • 5
  • 11
3

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'

Edit 2023: As @Elezar commented this could be unsafe to do for various reasons, so similar cases should be considere case by case.

Renetik
  • 5,887
  • 1
  • 47
  • 66
  • And I would like to know why webstom doesn't show me that I don't have import defined and don't suggest me import either... or how to get automatic imports working for my typescript extensions – Renetik May 10 '19 at 04:12
  • This looks promising, but perhaps you should cast the this value here toLower() and trim() it also first ? I like the prototype approach, for C# extension methods are akin – Tore Aurstad May 01 '21 at 21:29
  • There are some risks with updating the prototype of built-in objects. The first is that other code could be trying to add a function with the same name to the prototype. If that's the case, whichever is loaded last will be used. This can make for some very hard to diagnose bugs, especially if the implementations are only slightly different. The second problem is that a function with this name could be added to the ECMAScript standard for String at some point. Future developers would then be very confused on why this function behaves differently in this codebase than everywhere else. – Elezar Jul 10 '23 at 23:17
  • 1
    @Elezar I get you... I am mostly swift / kotlin dev so I probably was trying to replicate extensions here.. But looks like you should not do that. Its old answer so I leave it just as intresting idea for others. Would be cool if they make typescript on par with swift / kotlin to allow some high level of coding and ide support... – Renetik Jul 12 '23 at 09:26
  • @Renetik I understand. But the big difference between JS prototype changes and Swift extensions is that prototype changes are global. If your app uses 4 modules and you change the string prototype in moduleA, that change is going to affect the other 3 modules, even if they have nothing to do with moduleA. Or more insidiously, moduleB imports moduleQ, which imports moduleZ, which imports module42. And this 4th-level module42 suddenly works differently because the top-level app imported prototype changes from moduleA. It can be very difficult to debug. – Elezar Jul 18 '23 at 15:50
2

This function will convert your string to boolean

export const stringToBoolean = (str: string | null | undefined) => {
    if (!str) {
        return false
    }
    if (typeof str === "string") {
        return !["0", "false", "no", "n", "null", "undefined", "nil"].includes(str.toLowerCase().trim())
    }
    return Boolean(str)
}
  • 1
    This will return true for any string value that's not one of the 6 listed in the array. e.g., `stringToBoolean("foo")` will return true – Elezar Jul 10 '23 at 23:09
2

I think this is most accurate:

function parseBoolean(value?: string | number | boolean | null) {
    value = value?.toString().toLowerCase();
    return value === 'true' || value === '1';
}

I am not sure if its good idea to include No/Yes and Y kind of values because it could add more complexity and undesired results.

XzaR
  • 610
  • 1
  • 7
  • 17
-2

just use << !! >> operator:

const Text1 = ""
const Text2 = "there is a text"

console.log(!!Text1) // false
console.log(!!Text2) // true
-5

You could also try using the bang bang operator if you know its a valid boolean value in the string. for e.g.

let trueAsString = 'true';

let convertedStringToBool = !!trueAsString;

  • 1
    this only checks if the string is not an empty string, as soon as there is a character in the string the !! wil return true. Don't use this if you want to cast a string to boolean. `!!'true'; // true !!'false'; // true !!''; // false` – Youri Jul 21 '21 at 07:21
-6

You can use that:

let s: string = "true";
let b: boolean = Boolean(s);
Kevin Leto
  • 17
  • 4
-16

Boolean("true") will do the work too

Ishai
  • 169
  • 10