Contains case insensitive

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?

Solutions/Answers:

Solution 1:

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

Solution 2:

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)

Solution 3:

Use a RegExp:

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

Or, use .toLowerCase():

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

Solution 4:

There are a couple of approaches here.

If you want to perform a case-insensitive check for just this instance, do something like the following.

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

Alternatively, if you’re performing this check regularly, you can add a new indexOf()-like method to String, but make it case insensitive.

String.prototype.indexOfInsensitive = function (s, b) {
    return this.toLowerCase().indexOf(s.toLowerCase(), b);
}

// Then invoke it
if (referrer.indexOfInsensitive("Ral") == -1) { ...

Solution 5:

From ES2016 you can also use slightly better / easier / more elegant method:

if (referrer.includes("Ral")) { ... }

or

if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }

Here is some comparison of .indexOf() and .includes():
https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

Solution 6:

if (referrer.toUpperCase().indexOf("RAL") == -1) { ...