O'Reilly logo

JavaScript Cookbook by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

1.3. Conditionally Comparing Strings

Problem

You want to compare two strings to see if they’re the same.

Solution

Use the equality operator (==) within a conditional test:

var strName = prompt("What's your name?", "");

if (strName == "Shelley") {
   alert("Your name is Shelley! Good for you!");
} else {
   alert("Your name isn't Shelley. Bummer.");
}

Discussion

Two strings can be compared using the equality operator (==). When used within a conditional statement, a block of code is run if the test evaluates to true (the strings are equal):

if (strName == "Shelley") {
   alert("Your name is Shelley! Good for you!");
}

If the strings are not equal, the first statement following the conditional statement block is processed. If an if...else conditional statement is used, the block of code following the else keyword is the one that’s processed:

if (strName == "Shelley") {
   alert("Your name is Shelley! Good for you!");
} else {
   alert("Your name isn't Shelley. Bummer.");
}

There are factors that can influence the success of the string comparison. For instance, strings have case, and can consist of uppercase characters, lowercase characters, or a combination of both. Unless case is an issue, you’ll most likely want to convert the string to all lowercase or uppercase, using the built-in String methods toLowerCase and toUpperCase, before making the comparison, as shown in the following code:

var strName = prompt("What's your name?", "");

if (strName.toUpperCase () == "SHELLEY") {
   alert("Your name is Shelley! Good for you!");
} else {
   alert("Your name isn't Shelley. Bummer.");
}

Note that the toUpperCase method (and toLowerCase) do not take any parameters.

In Recipe 1.2, I discussed that data type conversion occurs automatically when concatenating a numeric or Boolean value, or a String object to a string. This same type of data type conversion also occurs with the equality operator if one value is a string. In the following, the number 10.00 is converted into the string “10”, and then used in the comparison:

var numVal = 10.00;
if (numVal == "10") alert ("The value is ten"); succeeds

There may be times, though, when you don’t want automatic data conversion to occur—when you want the comparison to fail if the values are of different data types. For instance, if one value is a string literal and the other is a String object, you might want the comparison to fail because the two variables are of different data types, regardless of their perspective values. In this case, you’ll want to use a different equality operator, the strict equality operator (===):

var  strObject = new  String("Shelley");

var  strLiteral  =  "Shelley";

if (strObject  ==  strLiteral) // this comparison succeeds

...

if (strObject === strLiteral) // fails because of different data types

The comparison fails if the two variables being compared are different data types, even though their primitive string values are the same.

Sometimes, you might want to specifically test that two strings are not alike, rather than whether they are alike. The operators to use then are the inequality operator (!=) and strict inequality operator (!==). They work in the same manner as the previous two operators just discussed, but return true when the strings are not alike:

var strnOne  =  "one";
var strnTwo  =  "two";
if (strnOne != strnTwo) // true, as they are not the same string value

The strict inequality operator returns true if the strings are not the same value or the data type of the two operands (values on either side of the operator) is different:

var strObject = new String("Shelley");
var strLiteral = "Shelley";
if (strObject !== strLiteral) // succeeds, because data type of operands differs

If you’re more interested in discovering how two strings may differ, you can use other comparison operators, as shown in Table 1-1.

Table 1-1. Comparison operators

Operator

Description

Example

Equality ==

True if operands are the same; otherwise false

var sVal = "this";
if (sVal == "this) // true

Strict equality ===

True if operands are the same, and the same data type; otherwise false

var sVal = "this";
var sVal2 = new String("this");

if (sVal === sVal2) // not true

Inequality !=

True if operands are not the same; otherwise false

var sVal = "this";
if (sVal == "that") // true

Strict inequality !==

True if operands are not the same, or are not the same data type; otherwise false

var sVal = "this";
var sVal2 = new String("this");

if (sVal !== sVal2) // true

Greater than >

True if first operand is greater in value than second operand

var sOne = "cat";
var sTwo = "dog";

if (sOne > sTwo) // false

Greater than or equal >=

True if first operand is greater than or equal to second operand

var sOne = "Cat";
var sTwo = "cat";

if (sOne >= sTwo) // true

Less than <

True if second operand is greater than first operand

var sOne = "cat";
var sTwo = "Cat";

if (sOne < sTwo) // true

Less than or equal <=

True if second operand is greater than or equal to first operand

var sOne = new String("cat");
var sTwo = "cat";

if (sOne <= sTwo) // equal, true

Comparison operators work numerically with numbers, but lexically with strings. For instance, the value “dog” would be lexically greater than “cat”, because the letter “d” in “dog” occurs later in the alphabet than the letter “c” in “cat”:

var sOne = "cat";
var sTwo = "dog"
if (sOne > sTwo // false, because "cat" is lexically less than "dog"

If two string literals only vary based on case, the uppercase characters are lexically greater than the lowercase letter:

var sOne  = "Cat";
var sTwo  = "cat";
if (sOne >=  sTwo) // true, because 'C' is lexically greater than 'c'

There is no strict greater than or strict less than operators, so it makes no difference if the data type of the operands differs:

var sOne = new String("cat");
var sTwo = "cat";
if (sOne <= sTwo) // both equal, so true, as data type doesn't matter

Before leaving this recipe, there is another approach you can use to compare strings, but this one has a little kick to it. It’s based on the String method, localeCompare.

The localeCompare method takes one parameter, a string, which is compared against the string value to which it is attached. The method returns a numeric value equal to 0 if the two strings are the same; –1 if the string parameter is lexically greater than the original string; 1 otherwise:

var fruit1 = "apple";
var fruit2 = "grape";
var i = fruit1.localeCompare(fruit2); // returns -1

For the most part, you’ll probably use the comparison operators rather than the localeCompare method, but it’s always interesting to see more than one approach.

See Also

For more on string-to-number conversion, see Recipe 4.5.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required