Compare Two Strings in JavaScript

 

You can use the localeCompare method to compare two strings in the current locale. Here's the syntax:

 

string1.localeCompare(string2)

 

  • 1 if string1 is greater (higher in the alphabetical order) than string2
  • -1 if string1 is smaller (lower in the alphabetical order) than string2
  • 0 if string1 and string2 are equal in the alphabetical order

 

 

Use the strict equality operator (===) to compare strings, eg 'string' === 'string'. The operator checks that the values ​​on the left and right sides are the same. The strict equality operator returns true if the values ​​are equal and false otherwise.

 

const str1 = 'abc';
const str2 = 'abc';

if (str1 === str2) {
  console.log('Strings are equal');
} else {
  console.log('Strings are NOT equal');
}

Tags:

Share:

Related posts