15

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?

atreju
  • 965
  • 6
  • 15
  • 36

4 Answers4

31

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)
Community
  • 1
  • 1
Andy
  • 61,948
  • 13
  • 68
  • 95
6

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

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

Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
  • 2
    But, as stated in an answer and comment, `==` does not even meet the requirement of checking for an exact match, at least not in the uninformed case. – Ingo Bürk Sep 03 '13 at 09:33
  • @IngoBürk Yeah I know. But still for cases when you do not need strict comparison == is faster. That's only an information, I showed the speeds and choosing the method is only up to you :) – Savas Vedova Sep 03 '13 at 09:52
  • Just what I needed. @IngoBürk, while you're *strictly* correct, I think the meaning of exact is highly contextual. – seebiscuit Jun 29 '15 at 18:03
2

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

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1
if (typeof string1=="string" && typeof string2=="string" && string1 === string2)

no escape method :)

kangoroo
  • 359
  • 2
  • 10