Compare two strings in JavaScript
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let x = 'ABC'; let y = 'ABD'; let ret = x.localeCompare(y) if (ret < 1) { console.log(`${x} occurs before ${y}`); } else if (ret > 1) { console.log(`${x} occurs after ${y}`); } else { console.log(`${x} is equivalent to ${y}`); } /* Output: ABC occurs before ABD */ |
2. Custom comparison function
You can also write our own comparison function to compare strings. The following code example shows how to implement this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function compare(x, y) { if (x < y) { return -1; } if (x > y) { return 1; } return 0; } let x = 'ABC'; let y = 'ABD'; let ret = compare(x, y); if (ret < 1) { console.log(`${x} occurs before ${y}`); } else if (ret > 1) { console.log(`${x} occurs after ${y}`); } else { console.log(`${x} is equivalent to ${y}`); } /* Output: ABC occurs before ABD */ |
You can shorten the above method to:
|
1 2 3 |
function compare(x, y) { return (x < y ? -1 : (x > y ? 1 : 0)); } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
var _ = require('underscore'); let x = 'ABC'; let y = 'ABC'; console.log(_.isEqual(x, y)); /* Output: true */ |
That’s all about comparing two strings in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)