Related Articles

Related Articles

JavaScript | Convert a string to boolean
  • Last Updated : 28 Mar, 2019

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:

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :