Javascript contains case insensitive

I have the following:

if (referrer.indexOf("Ral") == -1) { ... }

What I like to do is to make Ral case insensitive, so that it can be RAl , rAl , etc. and still match.

Is there a way to say that Ral has to be case-insensitive?


Add .toLowerCase() after referrer . This method turns the string in a lower case string. Then, use .indexOf() using ral instead of Ral .

if (referrer.toLowerCase().indexOf("ral") === -1) { 

The same can also be achieved using a Regular Expression (especially useful when you want to test against dynamic patterns):

if (!/Ral/i.test(referrer)) {
   //    ^i = Ignore case flag for RegExp

Another options is to use the search method as follow:

if (referrer.search(new RegExp("Ral", "i")) == -1) { ...

It looks more elegant then converting the whole string to lower case and it may be more efficient.
With toLowerCase() the code have two pass over the string, one pass is on the entire string to convert it to lower case and another is to look for the desired index.
With RegExp the code have one pass over the string which it looks to match the desired index.

Therefore, on long strings I recommend to use the RegExp version (I guess that on short strings this efficiency comes on the account of creating the RegExp object though)


Use a RegExp:

if (!/ral/i.test(referrer)) {
    ...
}

Or, use .toLowerCase() :

if (referrer.toLowerCase().indexOf("ral") == -1)
链接地址: http://www.djcxy.com/p/75190.html

上一篇: 如何忽略List <string>中的区分大小写

下一篇: Javascript包含大小写不敏感