How to convert string to boolean in typescript Angular 4

后端 未结 5 813
后悔当初
后悔当初 2021-01-31 13:33

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,No

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 14:03

    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/

提交回复
热议问题