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
, andh1
. - The
div
element is just a wrapper for the rest of the elements. - The inner text for the
button
element is“Show”
and for theh1
element is“Output”
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
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 andh1
element usingdocument.querySelector()
and stored them inbtnShow
andoutput
variables respectively. - We have 2 global variables
str1
andstr2
. They both hold 2 separate strings as their value. - We have attached the
click
event to thebutton
element. - In the event handler function, we are calling the
localeCompare()
method ofstr1
and passingstr2
as a parameter. We are storing the returning number in theresult
variable and displaying it in the console window using theconsole.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 theh1
element by using itsinnerText
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'; });