Horje
JavaScript Program to Compare Two Strings

In JavaScript, comparing two strings can be essential for performing tasks like user authentication. It can involve checking if the user has entered the same credentials as there are in the database. This article provides insights into comparing two strings in JavaScript. It explores four distinct approaches with detailed explanations and examples.

Using strict equality (===) operator

In this approach we define a function that compare two strings using the strict equality operator (===), which checks if both the value and the type of the operands are equal.

Example: The below code example uses the strict equality (===) operator to Compare two Strings in JavaScript.

JavaScript
function compareStrings(str1, str2) {
    if (str1 === str2) {
        return "Strings are equal";
    } else {
        return "Strings are not equal";
    }
}

console.log(compareStrings("hello", "hello"));

Output
Strings are equal

Using localeCompare( ) method

The localeCompare( ) method, which compares two strings based on the locale-sensitive comparison rules and returns:

  • A negative number if the first string comes before the second string.
  • Zero if the strings are equal.
  • A positive number if the first string comes after the second string.

Example: The below code example Uses the localeCompare( ) Method to Compare Two Strings in JavaScript.

JavaScript
function compareStrings(str1, str2) {
    let comparisonResult = str1.localeCompare(str2);
    if (comparisonResult === 0) {
        return "Strings are equal";
    } else if (comparisonResult < 0) {
        return `"${str1}" comes before "${str2}"`;
    } else {
        return `"${str1}" comes after "${str2}"`;
    }
}

console.log(compareStrings("apple", "banana"));

Output
"apple" comes before "banana"

Using includes() method

The includes() method check if one string includes the other string. It returns true if one string includes the other one, otherwise it return false.

Example: The below code example uses the includes() method to Compare two Strings in JavaScript.

JavaScript
function compareStrings(str1, str2) {
    if (str1.includes(str2)) {
        return `${str1} contains ${str2}`;
    } else {
        return `${str1} does not contain ${str2}`;
    }
}

console.log(compareStrings("hello world", "world"))

Output
hello world contains world

Using Regular Expression

Regular expressions compares two strings based on specific patterns or criteria. We can use Regular Expression to verify if two given strings are same or not. However, this method is not case sensitive.

Example: The below code example Uses the regular expressions Method to Compare Two Strings in JavaScript.

JavaScript
function compareStrings(str1, str2) {
    // Case insensitive regular expression
    let regex = new RegExp(str2, 'i');
    if (regex.test(str1)) {
        return `${str1} matches the pattern ${str2}`;
    } else {
        return `${str1} does not match the pattern ${str2}`;
    }
}

console.log(compareStrings("Hello", "hello"));

Output
Hello matches the pattern hello

Using normalize()

Using the normalize() method standardizes both strings to a common Unicode form before comparing them with the === operator. This approach ensures that strings with equivalent characters but different Unicode representations are considered equal.

Example:

JavaScript
function compareStrings(str1, str2) {
  return str1.normalize() === str2.normalize();
}


console.log(compareStrings("café", "cafe\u0301")); // Output: true
console.log(compareStrings("hello", "world")); // Output: false

Output
true
false

Using localeCompare() with Options

Another approach to comparing strings in JavaScript is using the localeCompare() method with options for more customized and sensitive comparisons. This method allows for various comparison criteria, such as sensitivity to accents, case, and more.

Example: Using localeCompare() with Options

JavaScript
function compareStringsWithOptions(str1, str2) {
    // Using localeCompare with options for case and accent sensitivity
    const options = { sensitivity: 'base' };
    return str1.localeCompare(str2, undefined, options) === 0;
}

const string1 = "Café";
const string2 = "cafe";

console.log(compareStringsWithOptions(string1, string2));

const string3 = "Hello";
const string4 = "hello";

console.log(compareStringsWithOptions(string3, string4)); 

Output
true
true



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Get an Object Value By Key in TypeScript How to Get an Object Value By Key in TypeScript
Check if an Object is Empty in TypeScript Check if an Object is Empty in TypeScript
JavaScript Program to Check Whether a Number is Perfect Square JavaScript Program to Check Whether a Number is Perfect Square
What is the use of as const assertion in TypeScript? What is the use of as const assertion in TypeScript?
How to Check Types in Typescript? How to Check Types in Typescript?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13