JavaScript Convert a string to boolean


To convert a string to boolean in JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Converting string to boolean</h1>
<button class="Btn">CLICK HERE</button>
<input class="str" type="text" />
<p class="sample"></p>
<h3>Click the above button to convert the string to boolean value</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let inputEle = document.querySelector(".str");
   document.querySelector(".Btn").addEventListener("click", () => {
      sampleEle.innerHTML += "Using == " + (inputEle.value == "true") + "<br>";
      sampleEle.innerHTML += "Using === " + (inputEle.value === "true") + "<br>";
   });
</script>
</body>
</html>

Output

On writing something in the input field other than string ‘true’ and clicking the button −

Updated on: 07-May-2020

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements