How to use Iterative Character Comparison In Javascript
Using iterative character comparison involves first checking if the lengths of the strings are equal. If they are, compare each character one by one using a loop. If all characters match, the strings are considered the same.
Example:
function areStringsSame(str1, str2) {
if (str1.length !== str2.length) return false;
for (let i = 0; i < str1.length; i++) {
if (str1[i] !== str2[i]) return false;
}
return true;
}
console.log(areStringsSame("hello", "hello")); // Output: true
console.log(areStringsSame("hello", "world")); // Output: false
Output
true false
JavaScript Program to Check if Two Strings are Same or Not
In this article, we are going to implement a JavaScript program to check whether two strings are the same or not. If they are the same then we will return true else we will return false.
Examples:
Input: str1 = Geeks, str2 = Geeks
Output: True. Strings are the Same
Input: str1 = Geeks, str2 = Geek
Output: False. Strings are not Same
Table of Content
- Using localCompare() Method
- Using startsWith() and endsWith() Methods
- Using the String.prototype.match() Method
- Using Array.from() and Array.prototype.join() Methods
- Using Iterative Character Comparison
Contact Us