Javascript String Compare
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.
Javscript 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:
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.
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 then 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.
Javscript 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:
By converting both strings to lower case 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.
|