Compare Two Strings
By Stephen Bucaro
In programming, the word "string" refers to an array of characters like a sentence
or a paragraph. You can compare two strings using == (the equality operator) as shown below.
var a = "yesterday";
var b = "Yesterday";
if(a == b)
alert("The strings are identical");
else
alert("The strings are different");
When we compare strings this way, we are simply comparing their ASCII or Unicode
data as if they were numeric values. This type of comparison is case sensitive.
In the example above, a comparison would say that the two strings are different
because of the case difference in the first letter. To return a positive result
each character in the first string must be the same case as the corresponding character
in the second string.
Java Script
provides a built-in string object that provides you with many methods for manipulating
strings. Proper coding would declare string variables as shown below.
var a = new String("yesterday");
var b = new String("Yesterday");
But strictly speaking, you don't have to declare the variables to be String objects
because when you put the left-value within paracentesis, Java Script automatically
stores them in String objects.
But what if we didn't care about case? The string object contains two methods;
toUppercase and toLowercase that lets you change the case of all the
characters in a string. The code below uses the toUppercase method to change
both strings to all uppercase characters before making a comparison.
var strOne = new String("yesterday");
var strTwo = new String("Yesterday");
if(strOne.toUpperCase() == strTwo.toUpperCase())
alert("The strings are identical");
else
alert("The strings are different");
In the example above, a comparison would say that the two stings are identical because
the toUppercase changed the value of strOne to "YESTERDAY" and the value of strTwo
to "YESTERDAY" before the comparison was made.
One common problem with string comparisons, especially when one of the strings was
acquired from a form textbox, is blank characters on the beginning or end of a string.
The Java Script object does not contain a built-in method to trim leading and trailing
blanks from a string.
function trimString(aString)
{
while(aString.substring(0,1) == ' ')
{
aString = aString.substring(1, aString.length);
}
while(aString.substring(aString.length - 1, aString.length) == ' ')
{
aString = aString.substring(0,aString.length-1);
}
return aString;
}
|