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.
<!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
filter_none
Output:
- Before click on the button:
- After click on the button:
Example 2: This example uses === operator to convert string to its boolean value.
<!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
filter_none
Output:
- Before click on the button:
- After click on the button: