Using localeCompare() Method
The localeCompare() method compares two strings based on the current locale. It’s case-sensitive by default and is particularly useful for sorting strings or checking the order of strings in lexicographical order.
Syntax
string1.localeCompare(string2, locale, options)
- locale: Optional. Specifies the locale for comparison. Defaults to the environment’s locale.
- options: Optional. Additional settings for comparison (e.g., sensitivity).
Example 1: Comparing Strings Lexicographically
const string1 = "apple";
const string2 = "banana";
const result = string1.localeCompare(string2);
if (result === 0) {
console.log("The strings are identical.");
} else if (result < 0) {
console.log("string1 comes before string2.");
} else {
console.log("string1 comes after string2.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
string1 comes before string2.
Example 2: Ignoring Case Sensitivity
const string1 = "Hello";
const string2 = "hello";
const result = string1.localeCompare(string2, undefined, { sensitivity: "base" });
if (result === 0) {
console.log("The strings are identical.");
} else {
console.log("The strings are different.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
The strings are identical.
This example shows how you can use localeCompare() to perform a case-insensitive comparison by setting the sensitivity option to base.
Using Regular Expression
Regular expressions (regex) are powerful tools for pattern matching and string manipulation. You can use them to compare strings based on specific patterns.
Syntax
regex.test(string)
Example 1: Checking for Exact Match
const string1 = "hello world";
const regex = /^hello world$/;
if (regex.test(string1)) {
console.log("The string matches the pattern.");
} else {
console.log("The string does not match the pattern.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
The string matches the pattern.
Example 2: Case-Insensitive Comparison
const string1 = "Hello";
const regex = /^hello$/i;
if (regex.test(string1)) {
console.log("The strings match (case-insensitive).");
} else {
console.log("The strings do not match.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
The strings match (case-insensitive).
Here, the i flag in the regex makes the comparison case-insensitive.
Check if a String Contains Another String
One of the most common tasks when working with strings in JavaScript is checking if one string contains another. This is useful in scenarios like searching for keywords, validating user input, or filtering data. JavaScript provides several methods to achieve this, & we’ll discuss them in detail.
Using `includes()` Method
The `includes()` method is the simplest way to check if a string contains another string. It returns `true` if the string is found & `false` otherwise. Let’s see how it works:
let mainString = "Hello, welcome to JavaScript programming!";
let searchString = "JavaScript";
if (mainString.includes(searchString)) {
console.log("The string contains 'JavaScript'.");
} else {
console.log("The string does not contain 'JavaScript'.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output
The string contains 'JavaScript'.
In this code:
- `mainString` is the string we’re searching in.
- `searchString` is the string we’re looking for.
- The `includes()` method checks if `searchString` exists in `mainString`.
- If it does, it logs "The string contains 'JavaScript'." Otherwise, it logs "The string does not contain 'JavaScript'."
Using `indexOf()` Method
Another way to check if a string contains another string is by using the `indexOf()` method. This method returns the index of the first occurrence of the search string. If the string is not found, it returns `-1`.
let mainString = "Learning JavaScript is fun!";
let searchString = "fun";
if (mainString.indexOf(searchString) !== -1) {
console.log("The string contains 'fun'.");
} else {
console.log("The string does not contain 'fun'.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output
The string contains 'fun'.
In this code:
- `indexOf()` searches for `searchString` in `mainString`.
- If the result is not `-1`, it means the string is found.
- This method is useful when you also need the position of the string.
How to Compare two Strings in Javascript Using localeCompare()?
The localeCompare() method provides more advanced options for comparing strings beyond simple equality. Here are some steps to use it effectively:
- Understand the Result:
- 0: The strings are equal.
- Negative value: The first string comes before the second.
- Positive value: The first string comes after the second.
- Set Options for Advanced Comparison: Use the options parameter to customize the comparison:
- sensitivity: Determines case and accent sensitivity (e.g., base, accent, case).
- ignorePunctuation: Ignores punctuation during comparison.
Example: Advanced Comparison
const string1 = "cafe";
const string2 = "café";
const result = string1.localeCompare(string2, "en", { sensitivity: "accent" });
if (result === 0) {
console.log("The strings are identical.");
} else {
console.log("The strings are different.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
The strings are different.
In this example, the localeCompare() method recognizes the difference between "e" and "é" (e with an accent) when the sensitivity is set to accent
Frequently Asked Questions
What is the difference between == and === for string comparison in JavaScript?
The == operator compares values after type conversion, while === checks both value and type without any type conversion.
How does localeCompare() handle case sensitivity?
By default, localeCompare() is case-sensitive. However, you can customize it using the sensitivity option, such as setting it to base for case-insensitive comparisons.
Can regular expressions compare strings for exact matches?
Yes, regular expressions can compare strings for exact matches and also support advanced pattern matching. Use the test() method for this purpose.
Conclusion
Comparing two strings in JavaScript is an important skill that can be achieved using various methods. The strict equality operator (===) is ideal for exact, case-sensitive comparisons. The localeCompare() method is versatile and supports locale-sensitive comparisons with advanced options. Regular expressions offer flexibility for pattern matching and case-insensitive comparisons.