Algorithm


  1. Input:

    • Receive two strings as input.
  2. Initialization:

    • Initialize variables to store the two strings.
  3. Length Check:

    • Compare the lengths of the two strings.
    • If lengths are not equal, the strings are not equal.
  4. Character Comparison Loop:

    • Use a loop to iterate through each character of the strings.
    • Compare characters at corresponding positions.
    • If a mismatch is found, the strings are not equal.
  5. Equality Check:

    • After the loop, if no mismatches were found, the strings are equal.
  6. Output:

    • Return a boolean indicating whether the strings are equal or not.

 

Code Examples

#1 Code Example- Using toUpperCase()

Code - Javascript Programming

// js program to perform string comparison

const string1 = 'JavaScript Program';
const string2 = 'javascript program';

// compare both strings
const result = string1.toUpperCase() === string2.toUpperCase();

if(result) {
    console.log('The strings are similar.');
} else {
    console.log('The strings are not similar.');
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
The strings are similar.

#2 Code Example- JS String Comparison Using RegEx

Code - Javascript Programming

// program to perform string comparison

const string1 = 'JavaScript Program';
const string2 = 'javascript program';

// create regex
const pattern = new RegExp(string1, "gi");

// compare the stings
const result = pattern.test(string2)

if(result) {
    console.log('The strings are similar.');
} else {
    console.log('The strings are not similar.');
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
The strings are similar.

#3 Code Example- Using localeCompare()

Code - Javascript Programming

// program to perform case insensitive string comparison

const string1 = 'JavaScript Program';
const string2 = 'javascript program';

const result = string1.localeCompare(string2, undefined, { sensitivity: 'base' });

if(result == 0) {
    console.log('The strings are similar.');
} else {
    console.log('The strings are not similar.');
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
The strings are similar.
Advertisements

Demonstration


JavaScript Programing to Compare Two Strings-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way