How to Compare Two Strings in Javascript

In this tutorial, you will learn how to compare two strings in javascript. The string is one of the built-in types in javascript and when it comes to web development, text content plays a major role.

When we talk about string comparison, we simply want to know if two strings are equal or not. There are numerous ways to compare strings, but I will demonstrate one of the simplest possible ways to accomplish this.

For any string in javascript, we have a built-in method localeCompare(). This method returns a number and that number indicates whether a reference string comes before, or after, or is the same as the given string in the sort order. We can leverage this method to compare strings.

In the following example, we have 2 hardcoded strings and upon button click, we will check if they are equal or not. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file and that includes div, button, and h1.
  • The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Show” and for the h1 element is “Output”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div class="container">
        <button>Show</button>
        <h1>Output</h1>
    </div>
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

.container {
    display: inline-block;
}

Javascript

  • We have selected button element and h1 element using document.querySelector() and stored them in btnShow and output variables respectively.
  • We have 2 global variables str1 and str2. They both hold 2 separate strings as their value.
  • We have attached the click event to the button element.
  • In the event handler function, we are calling the localeCompare() method of str1 and passing str2 as a parameter. We are storing the returning number in the result variable and displaying it in the console window using the console.log() method.
  • We are check if the result is equal to 0. If yes, that means both the strings are equal.  Depending upon the result of the check, we are displaying "Equal" or "Not Equal" in the h1 element by using its innerText property.
let btnShow = document.querySelector('button');
let output = document.querySelector('h1');

let str1 = 'abce';
let str2 = 'abcd';

btnShow.addEventListener('click', () => {
    let result = str1.localeCompare(str2);
    console.log(result);
    output.innerText = result == 0 ? 'Equal' : 'Not Equal';
});