This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
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.
The post How to Do Case-Insensitive String Comparison in Javascript appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
Ariessa Norramli | Sciencx (2021-02-21T10:42:00+00:00) How to Do Case-Insensitive String Comparison in Javascript. Retrieved from https://www.scien.cx/2021/02/21/how-to-do-case-insensitive-string-comparison-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.