This quick tutorial will show you how to compare two or more strings in the JavaScript programming language – optionally ignoring case – with code examples.
What are Strings?
Strings are a series of characters. Each character has an ordered position in the string. A string can be of any length – from 0 (zero) characters to as many as you need until your computer runs out of memory.
Strings are a type of variable. String type variables in JavaScript are variables that can hold a string value.
Comparing Strings in JavaScript
The JavaScript == operator checks whether two values are equal but ignores the type of the value or variable being compared.
Combined with an if statement, it can be used to compare strings and perform an action if they match:
var string1 = "hello"; var string2 = "goodbye"; if(string1 == string2){ //Strings match } else { //Strings do not match }
It’s possible to check whether two strings do not match by checking for inequality using the != operator:
var string1 = "hello"; var string2 = "goodbye"; if(string1 != string2){ //Strings do not match } else { //Strings match }
Equality checks can be chained, so you can compare many strings at the same time:
var string1 = "hello"; var string2 = "goodbye"; var string3 = "back again"; if(string1 == string2 == string3){ //Strings match } else { //Strings do not match }
Above, all strings must match for the if statement to succeed.
Ignoring Case When Comparing Strings in JavaScript
The toLowerCase() method is available to all JavaScript string variables and will return the characters in the string to lower case.
It does not modify the string variable’s value, so it can be used to compare strings, ignoring case, without altering the variables being compared.
var string1 = "hello"; var string2 = "HeLlO"; if(string1.toLowerCase() == string2.toLowerCase()){ //Strings match, ignoring case } else { //Strings do not match, ignoring case }
As all of the strings being compared will be converted to lower case for the comparison, the case is ignored.