Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the best way to compare two strings in JavaScript?
To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.
Example
You can try to run the following code to compare two strings
<!DOCTYPE html>
<html>
<body>
<button onclick="compareStr()">Compare Strings</button>
<p id="test"></p>
<script>
function compareStr() {
var string1 = "World";
var string2 = "World";
var result = string1.localeCompare(string2);
document.getElementById("test").innerHTML = result;
}
</script>
</body>
</html>Advertisements