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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read