JavaScript Compare String Examples

JavaScript compare strings; Through this tutorial, i am going to show you how to compare two or more strings in JavaScript using the equality operator and localeCompare method with examples.

Compare String JavaScript

In this tutorial, i am going to show you two ways for compare two strings in JavaScript; as shown below:

  • 1 – javascript compare strings Equality Operator Method
  • 2 – javascript Compare Strings localeCompare() Method

1 – javascript compare strings Equality Operator Method

The javascript equality operator is used to compare two values on both sides and it will return the result as true or false.

Syntax of javaScript Equality Operator

See the following syntax of javaScript equality operator; as shown below:

 ==

Example 1 – JavaScript Compare String using Equality Operator

To comparison string using equality operator in javaScript; as shown below example:

    var stringFirst = "javascript world";
    var stringSecond = "javascript world";
    var res = '';
    if(stringFirst == stringSecond)
    {
      res = 'strings are equal';
    }else
    {
      res = 'strings are not equal';
    }
    document.write( "Output :- " + res ); 

Output :- strings are equal

Remember some points of JavaScript Equality Operator

  • If this method returns true, strings are equal.
  • If this method returns false, strings are not equal

2 – JavaScript Compare Strings localeCompare() Method

The javascript localeCompare() method is used to on a string object for comparing two strings.

Syntax of JavaScript localeCompare() Method

See the following syntax of JavaScript localeCompare() method:

string.localeCompare(compareString);

Note:- this method will return 0, -1 or 1. This method does case-sensitive comparing.

Example 1 – JavaScript Compare Strings using localeCompare() Method

    var stringFirst = "javascript world";
    var stringSecond = "javascript world";
  
    var res = stringFirst.localeCompare(stringSecond);
    document.write( "Output :- " + res + "<br>"); 
    var stringThird = "javascript world";
    var stringFourth = "javascript";
  
    var res1 = stringThird.localeCompare(stringFourth);
    document.write( "Output :- " + res1 ); 

Result of the above code is:

Output :- 0
Output :- 1

Remember some points of localeCompare() method

  • If this method returns 0, the string is sorted before the compare string
  • Returns -1 by this method, the string is sorted after the compare string
  • If this method returns 1, two strings are not equal

More JavaScript Tutorials

Leave a Comment