JavaScript Program to Check if Two Strings are Same or Not
Last Updated :
19 Jul, 2024
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
Using localCompare() Method
In this approach, we are using the localCompare() method in JavaScript. This method is mainly used to compare the two strings according to their locale-specific collation order. If the strings are the same, then 0 is returned; otherwise, -1 or 1 is returned.
Syntax:
str1.localeCompare(str2)
Example: This example shows the use of the above-explained approach.
JavaScript
const sameStrings = (
inputString1,
inputString2) => {
return (
inputString1.localeCompare(
inputString2 ) === 0
);};
console.log(
sameStrings("Geeks", "Geeks")
);
Using startsWith() and endsWith() Methods
In this approach, we are using the startsWith() and endsWith() methods in JavaScript. Here, we are checking if str1 starts and ends with str2. If both considerations are satisfied, then the strings are the same when they are not the same.
Syntax:
str1.startsWith(str2) && str1.endsWith(str2)
Example: This example shows the use of the above-explained approach.
JavaScript
const stringsSame = (
inputString1,
inputString2) => {
return (
inputString1.startsWith(
inputString2
) &&
inputString2.endsWith(
inputString1
)
);};
console.log(
stringsSame("Geeks", "Geeks")
);
Using the String.prototype.match() Method
In this approach, we are using the match() method along with the regular expression. Here we are checking if str1 is the same as str2 using the regular expression pattern. If they are the same, then the true message is printed; otherwise, the false method is printed.
Syntax:
str1.match(new RegExp(`^${str2}$`)) !== null
Example: This example shows the use of the above-explained approach.
JavaScript
const sameString = (
inputString1,
inputString2) => {
return (
inputString1.match(
new RegExp(
`^${inputString2}$`
)
) !== null
);};
console.log(
sameString("geeks", "geeks")
);
Using Array.from() and Array.prototype.join() Methods
In this approach, we are using the from() and join() methods in JavaScript. Here, we are converting the input strings into an array of characters, then comparing these characters using the (===) operator, and then joining them back to strings. If the strings are the same, then the output is true; otherwise, it is false.
Syntax:
Array.from(str1).join('') === Array.from(str2).join('')
Example: This example shows the use of the above-explained approach.
JavaScript
const sameString = (
inputString1,
inputString2 ) => {
return (
Array.from(inputString1).join(
"") ===
Array.from(inputString2).join(
"")
);};
console.log(
sameString("geeks", "geeks")
);
Using Iterative Character Comparison
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:
JavaScript
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
Using localeCompare() with Case-Insensitive Comparison
In this approach, we use the localeCompare() method to compare the two strings after converting them to lowercase. This ensures that the comparison is case-insensitive.
Example: This example demonstrates the use of the localeCompare() method for case-insensitive comparison.
JavaScript
const sameStringsIgnoreCase = (inputString1, inputString2) => {
return inputString1.toLowerCase().localeCompare(inputString2.toLowerCase()) === 0;
};
console.log(sameStringsIgnoreCase("Geeks", "geeks")); // Output: true
console.log(sameStringsIgnoreCase("Geeks", "Geek")); // Output: false
Using JSON.stringify Method
In this approach, we use the JSON.stringify method to convert the strings into their JSON string representations and then compare them. If they are the same, the output is true; otherwise, it is false.
Example: This example shows the use of the above-explained approach.
JavaScript
const sameStringsUsingJSONStringify = (inputString1, inputString2) => {
return JSON.stringify(inputString1) === JSON.stringify(inputString2);
};
console.log(sameStringsUsingJSONStringify("Geeks", "Geeks"));
console.log(sameStringsUsingJSONStringify("Geeks", "Geek"));
Using localeCompare with Sensitivity Options and Ignoring Punctuation
In this approach, we will use the localeCompare method with options to consider sensitivity and ignoring punctuation. This is particularly useful when comparing strings with diacritics or different case and punctuation.
Example: This example demonstrates the use of the localeCompare method with sensitivity options and ignoring punctuation to compare two strings.
JavaScript
const sameStringsIgnorePunctuation = (inputString1, inputString2) => {
return inputString1.localeCompare(inputString2, undefined, { sensitivity: 'base', ignorePunctuation: true }) === 0;
};
console.log(sameStringsIgnorePunctuation("café", "cafe")); // Output: true
console.log(sameStringsIgnorePunctuation("Geeks!", "Geeks")); // Output: true
console.log(sameStringsIgnorePunctuation("Geeks", "Geek")); // Output: false
Similar Reads
JavaScript Program to Check if Two Arrays are Equal or Not
Given two arrays, arr1 and arr2 of equal length N, the task is to find if the given arrays are equal or not. Two arrays are said to be equal if: Both of them contain the same set of elements, Arrangements (or permutations) of elements might/might not be the same.If there are repetitions, then counts
4 min read
JavaScript Program to Compare Two Strings
These are the followings ways to compare two strings: 1. Using strict equality (===) operatorWe have defined 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. [GFGTABS] JavaScript let str1 = "hell
2 min read
JavaScript Program to Check Whether the String is Symmetrical or Not
In this article, we will see how to check whether the given string is symmetric or not. The symmetrical string is one that is similar from the starting to mid and mid to end. Example: Input: khokhoOutput: The entered string is symmetricalInput: madamOutput: The entered string is not symmetricalInput
3 min read
JavaScript Program to Check if Two Numbers have Same Last Digit
In this article, we will discuss how to check if two numbers have the same last digit in JavaScript. Checking the last digit of a number is a common requirement in programming tasks, and it can be useful in various scenarios. We will explore an approach using JavaScript to accomplish this task. Meth
4 min read
JavaScript Program to Find Uncommon Characters of the two Strings
In JavaScript, finding uncommon characters in two strings is the process of identifying the characters that exist in one string but not in the other string. We can find these uncommon characters using various approaches that are mentioned below: Table of Content Using SetsUsing Array.filter() method
2 min read
JavaScript Program to Check for Palindrome String using Recursion
Given a string, write a recursive function that checks if the given string is a palindrome, else, not a palindrome. A string is called a palindrome if the reverse of the string is the same as the original one. For example - âmadamâ, âracecarâ, etc. What is Recursion?The process in which a function c
3 min read
JavaScript to Check if all Levels of Two Trees are Anagrams or Not
In this article, we are going to learn about Checking if all levels of two trees are anagrams or not. Checking if all levels of two trees are anagrams means verifying that for each level in two binary trees, the nodes at that level have the same characters with the same frequencies, indicating that
3 min read
JavaScript Program to Print All Duplicate Characters in a String
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = âgeeksforgeeksâOutput:e, count = 4g, count = 2k, count = 2s, count = 2Ta
5 min read
JavaScript Program Count number of Equal Pairs in a String
In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
3 min read
JavaScript Program to Find the First Repeated Word in String
Given a string, our task is to find the 1st repeated word in a string. Examples: Input: âRavi had been saying that he had been thereâOutput: hadInput: âRavi had been saying thatâOutput: No RepetitionBelow are the approaches to Finding the first repeated word in a string: Table of Content Using SetUs
4 min read