
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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>
- Related Articles
- What is the best way to concatenate strings in JavaScript?
- What is the best way to add an event in JavaScript?
- What is the best way to initialize a JavaScript number?
- How to compare two strings in the current locale with JavaScript?
- What is the best way to do optional function parameters in JavaScript?
- What is the best way to break from nested loops in JavaScript?
- What is the best way to initialize a JavaScript Date to midnight?
- What is the best way of declaring multiple Variables in JavaScript?
- What is the best way to convert a number to a string in JavaScript?
- Compare two Strings in Java
- Program to Compare two strings in Java
- How to compare two strings in Golang?
- What is the best way to handle a Javascript popup using Selenium Webdriver?
- Compare the two Strings lexicographically in Java
- Java Program to Compare Two Strings

Advertisements