Algorithm
-
Input:
- Receive two strings as input.
-
Initialization:
- Initialize variables to store the two strings.
-
Length Check:
- Compare the lengths of the two strings.
- If lengths are not equal, the strings are not equal.
-
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.
-
Equality Check:
- After the loop, if no mismatches were found, the strings are equal.
-
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
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
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
The strings are similar.
Demonstration
JavaScript Programing to Compare Two Strings-DevsEnv