views:

1433

answers:

2

How do I perform case insensitive string comparison in Javascript.

+3  A: 

The simplest way to do it (if you're not worried about special Unicode characters) is to call toUpperCase:

var areEqual = string1.toUpperCase() === string2.toUpperCase();
SLaks
this is good enough for me - but just being curious, how would this not work with special Unicode chars?
flybywire
Conversion to upper or lower case does provide correct case insensitive comparisons in all languages. http://www.i18nguy.com/unicode/turkish-i18n.html
Sam
@sam: I know. That's why I wrote `if you're not worried about special Unicode characters`.
SLaks
A: 

The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the 'i' flag.

http://stackoverflow.com/questions/177719/javascript-case-insensitive-search

When both strings being compared are variables (not constants), then it's a little more complicated 'cause you need to generate a RegExp from the string but passing the string to RegExp constructor can result in incorrect matches or failed matches if the string has special regex characters in it.

If you care about internationalization don't use toLowerCase() or toUpperCase() as it doesn't provide accurate case-insensitive comparisons in all languages.

http://www.i18nguy.com/unicode/turkish-i18n.html

Sam
wow, and I thought I was asking a trivial question...
flybywire