JavaScript Convert a string to boolean

JavascriptWeb DevelopmentObject Oriented Programming

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 −

raja
Published on 07-May-2020 14:06:27
Advertisements