This post will discuss how to compare two strings in JavaScript.

1. Using localeCompare() method

The localeCompare() method compares a string to another string and returns an integer indicating whether the string comes before, after, or equivalent to the specified string. It returns a negative number if the string occurs before the compare string; positive if the string occurs after the compare string; 0 if both strings are equivalent.

Download  Run Code

2. Custom comparison function

You can also write our own comparison function to compare strings. The following code example shows how to implement this:

Download  Run Code

 
You can shorten the above method to:

3. Using Underscore/Lodash Library

If you’re using the Underscore or Lodash library, consider using the _.isEqual method. It performs a deep comparison between two values to determine whether they are equivalent.

Download Code

That’s all about comparing two strings in JavaScript.