In this example you will learn how to compare two strings in javascript using if condition
Basic Example:
1 2 3 4 5 6 7 8 9 10 11 |
<script> string1="Hello"; string2="World"; if(string1 == string2) window.alert("Equal"); else window.alert("Not Equal"); </script> |
Example 2 Form Design: Design HTML as follows: I design HTML page using bootstrap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Code4Example.com</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <form> <div class="form-group"> <label for="string1">Enter First:</label> <input type="text" class="form-control" id="string1"> </div> <div class="form-group"> <label for="string2">Enter Second:</label> <input type="text" class="form-control" id="string2"> </div> <div class="alert alert-success" id="result"> </div> <button type="button" id="compareBtn" class="btn btn-primary">Compare</button> </form> </div> <script> var compareBtn=document.querySelector("#compareBtn"); compareBtn.onclick=function(){ var string1=document.querySelector("#string1"); var string2=document.querySelector("#string2"); var resultDiv=document.querySelector("#result"); if(string1.value == string2.value) resultDiv.innerHTML="Equal"; else resultDiv.innerHTML="Not Equal"; } </script> </body> </html> |
Output: