javascript compare strings. In this tutorial, we will demonstrate, how you can compare two strings in javascript using the equality operator and localeCompare method with the definition of this method, syntax, parameters, and several examples.
In this tutorial, we will explain two methods of javascript to compare two strings in javascript. Let’s see the method below:
You can use the equality operator of javascript to compare two strings in javascript
Definition:- The javascript equality operator, which is used to compare two values on both sides and it will return the result as true or false.
==
var strFirst = "javascript world";
var strSecond = "javascript world";
var res = '';
if(strFirst == strSecond)
{
res = 'strings are equal';
}else
{
res = 'strings are not equal';
}
document.write( "Output :- " + res );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>javascript string compare</title>
</head>
<body>
<script type = "text/javascript">
var strFirst = "javascript world";
var strSecond = "javascript world";
var res = '';
if(strFirst == strSecond)
{
res = 'strings are equal';
}else
{
res = 'strings are not equal';
}
document.write( "Output :- " + res );
</script>
</body>
</html>
Result of the above code is:
Output :- strings are equal
You can use the localeCompare() Method of javascript to compare two strings in javascript.
**Definition:**The javascript localeCompare() method is used to on a string object for comparing two strings.
string.localeCompare(compareString);
Note:- this method will return 0, -1 or 1. This method does case-sensitive comparing.
var strFirst = "javascript world";
var strSecond = "javascript world";
var res = strFirst.localeCompare(strSecond);
document.write( "Output :- " + res + "<br>");
var strThird = "javascript world";
var strFourth = "javascript";
var res1 = strThird.localeCompare(strFourth);
document.write( "Output :- " + res1 );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>javascript string compare | javascript localeCompare() Method</title>
</head>
<body>
<script type = "text/javascript">
var strFirst = "javascript world";
var strSecond = "javascript world";
var res = strFirst.localeCompare(strSecond);
document.write( "Output :- " + res + "<br>");
var strThird = "javascript world";
var strFourth = "javascript";
var res1 = strThird.localeCompare(strFourth);
document.write( "Output :- " + res1 );
</script>
</body>
</html>
Result of the above code is:
Output :- 0
Output :- 1
#javascript #programming