Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to test two strings for exact match in JavaScript

I want to compare two strings in JavaScript to test if they are exactly the same. Which would be the best (fastest) way to do this?

Right now, I'm considering either

if(string1.localeCompare(string2) == 0) {}

or simply

if(string1 == string2)

Is there a better way do to this?

like image 922
atreju Avatar asked Sep 03 '13 09:09

atreju


People also ask

Can we compare two strings using == in JavaScript?

Explanation of the example: In the above example, when str1 and str2 are compared after using the toUpperCase method, the expression JAVASCRIPT == JAVASCRIPT would return true as they are the same strings after both being in upper case. Here, the equality operator (==) is used to check if both the strings are the same.

Which method is used to match two strings JavaScript?

The localeCompare() method compares two strings in the current locale. The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).

How fast is string comparison in JavaScript?

String equality is slightly faster at 13.15ms vs BigInt at 16.57ms for 100k comparisons.


3 Answers

I would probably use strict equality if you want to check they are exactly the same, ie they're the same type too, just in case.

if (string1 === string2)
like image 148
Andy Avatar answered Oct 17 '22 17:10

Andy


Check this fiddle* and figure out yourself which one is faster.

*In case the link dies in the future: == > === > String.localeCompare (tested on Chrome).

like image 6
Savas Vedova Avatar answered Oct 17 '22 15:10

Savas Vedova


I'm not sure there is any room to optimize if(string1 == string2). That is the best approach.

like image 2
Kevin Bowersox Avatar answered Oct 17 '22 17:10

Kevin Bowersox