javascript

How to Do Case-Insensitive String Comparison in Javascript


In this article, you will learn how to do case-insensitive string comparison in Javascript.

Let’s say you have 2 string variables.

// A string variable named 'a' with value "codesource"
var a = "codesource";

// A string variable named 'b' with value "CODESOURCE"
var b = "CODESOURCE";

In order to do case-insensitive string comparison, you can use the String.localeCompare() method. In this example, you will be doing a comparison between two strings using English as locale and sensitivity equals to base. Strings that have the same base letters, regardless of its letter case will be considered as equal.

// A string variable named 'a' with value "codesource"
var a = "codesource";

// A string variable named 'b' with value "CODESOURCE"
var b = "CODESOURCE";

// Compare strings in English locale based on the difference in base letters
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
// => 0

Note: The String.localeCompare() method functions by returning a number that indicates whether a reference string occurs before, after or equals to the supplied string. This method will return 0 if the reference string and supplied string are equivalent to each other. A negative number is returned if the reference string comes before the supplied string. A positive number is returned if the reference string comes after the supplied string.


Share on social media

//