Comparing strings in JavaScript is quite easy, as long as you know about the equals operator and the JavaScript If Statement. This is all you need to know to find out if two strings of your choosing are equal.
Comparing one String to another String
Below we have created a fake authentication system and use an if statement to see if the user's name will grant them access to a special message.JavaScript Code:
<script type="text/javascript"> var username = "Agent006"; if(username == "Agent007") document.write("Welcome special agent 007"); else document.write("Access Denied!"); document.write("<br /><br />Would you like to try again?<br /><br />"); // User enters a different name username = "Agent007"; if(username == "Agent007") document.write("Welcome special agent 007"); else document.write("Access Denied!"); </script>
Display:
Access Denied!
Would you like to try again?
Welcome special agent 007
Be sure you realize that when you are comparing one string to another, you use two equals operators "==" instead of just one "=". When you use two equals operators, it means you are comparing two values.Would you like to try again?
Welcome special agent 007
In this case, the English translation of our program would be: "If username is equal to Agent007, then print out a welcome message; otherwise, access is denied."
Case Insensitive String Compare
Above, we used a case sensitive compare, meaning that if the capitalization wasn't exactly the same in both strings, the if statement would fail. If you would like to just check that a certain word is entered, without worrying about the capitalization, use the toLowerCase function.JavaScript Code:
<script type="text/javascript"> var username = "someAgent"; if(username == "SomeAgent") document.write("Welcome special agent"); else document.write("Access Denied!"); // Now as case insensitive document.write("<br /><br />Let's try it with toLowerCase<br /><br />"); if(username.toLowerCase() == "SomeAgent".toLowerCase()) document.write("Welcome special agent"); else document.write("Access Denied!"); </script>
Display:
Access Denied!
Let's try it with toLowerCase
Welcome special agent
By converting both strings to lowercase, we were able to remove the problem of it failing to find a match when the capitalization was slightly off. In this case, the "s" was capitalized in the username, but not capitalized in our if statement check.Let's try it with toLowerCase
Welcome special agent
0 comments
একটি মন্তব্য পোস্ট করুন