How do I perform case insensitive string comparison in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- how to split a list into a given number of sub-lis
if you are concerned about the direction of the inequality (perhaps you want to sort a list) you pretty-much have to do case-conversion, and as there are more lowercase characters in unicode than uppercase toLowerCase is probably the best conversion to use.
Javascript seems to use locale "C" for string comparisons so the resulting ordering will be ugly if the strings contain other than ASCII letters. there's not much that can be done about that without doing much more detailed inspection of the strings.
If both strings are of the same known locale, you may want to use
Intl.Collator
object like this:Obviously, you may want to cache the
Collator
for better efficiency.The advantages of this approach is that it should be much faster than using RegExps and is based on an extremely customizable (see description of
locales
andoptions
constructor parameters in the article above) set of ready-to-use collators.use regix for string match or comparison ,
in javaScript , you can use match() for string comparison , dont forget to put i in regix
example :
There are two ways for case insensitive comparison:
===
). How strict operator treats operands read stuff at: http://www.thesstech.com/javascript/relational-logical-operatorsUse the "search" string method for case insensitive search. Read about search and other string methods at: http://www.thesstech.com/pattern-matching-using-string-methods
Lots of answers here, but I like to add a sollution based on extending the String lib:
This way you can just use it like you do in Java!
Example:
Output will be:
Since no answer clearly provided a simple code snippet for using
RegExp
, here's my attempt:It has several advantages:
undefined
for example, would crash an expression likestr1.toUpperCase()
).RegExp
string.