JavaScript | Convert a string to boolean

Sometimes it is needed to convert a string representing boolean value “true”, “false” into intrinsic type of JavaScript. Given a string and the task is to convert given string to its boolean value.

Example 1: This example uses == operator to convert string to its boolean value.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
  
<head
    <title
        Convert string to boolean
    </title>
</head
          
<body style = "text-align:center;"
      
    <h1 style = "color:green;"
        GeeksForGeeks 
    </h1
          
    <input id = "input" type="text" name="input"/> 
      
    <button onclick="convertToBoolean()"
        Click to convert
    </button
      
    <h3 id = "div" style="color: green"></h3>
      
    <!-- Script to convert string to its
        boolean value -->    
    <script
        function convertToBoolean() {
            var input = document.getElementById("input");
            var x = document.getElementById("div");
            var str = input.value;
            x.innerHTML = str == 'true';
        }
    </script
</body
  
</html>                    

chevron_right


Output:



  • Before click on the button:
  • After click on the button:

Example 2: This example uses === operator to convert string to its boolean value.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
  
<head
    <title
        Convert string to boolean
    </title>
</head
          
<body style = "text-align:center;"
      
    <h1 style = "color:green;"
        GeeksForGeeks 
    </h1
              
    <input id = "input" type="text" name="input"/> 
      
    <button onclick="convertToBoolean()"
        Click to convert
    </button
      
    <h3 id = "div" style="color: green"></h3>
      
    <!-- Script to convert string to its
        boolean value -->
    <script
        function convertToBoolean() {
            var input = document.getElementById("input");
            var x = document.getElementById("div");
            var str = input.value;
            x.innerHTML = str === 'true';
        }
    </script
</body
  
</html>                    

chevron_right


Output:

  • Before click on the button:
  • After click on the button:


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.