javascript includes() case insensitive

JavascriptRegex

Javascript Problem Overview


I have an array of strings that I need to loop and check against with another passed in string.

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = localStorage.getItem("passedinstring");

for (i = 0; i < filterstrings.lines.length; i++) {
	if (passedinstring.includes(filterstrings[i])) {
	    alert("string detected");
	}
}

How do I ensure that case sensitivity is ignored here (preferably by using regex) when filtering, if the var passedinstring were to have strings like FirsTsTriNg or fiRSTStrING?

Javascript Solutions


Solution 1 - Javascript

You can create a RegExp from filterstrings first

var filterstrings = ['firststring','secondstring','thridstring'];
var regex = new RegExp( filterstrings.join( "|" ), "i");

then test if the passedinstring is there

var isAvailable = regex.test( passedinstring ); 

Solution 2 - Javascript

You can simply convert the passedinstring to lowercase.

var passedinstring = localStorage.getItem("passedinstring").toLowerCase();

Solution 3 - Javascript

ES6 array method filter() can simplify the solution to a single line. Use includes() method to determine whether an array includes a certain value among its entries in conjunction to the toLowerCase() method to convert it to lowercase.

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = localStorage.getItem("passedinstring");

// convert each string from filterstrings and passedinstring to lowercase
// to avoid case sensitive issue.
filteredStrings = filterstrings.filter((str) => str.toLowerCase().includes(passedinstring.toLowerCase())

Solution 4 - Javascript

convert filterstring and passedinstring to lowercase and compare

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = 
localStorage.getItem("passedinstring").toLowerCase();

for (i = 0; i < filterstrings.lines.length; i++) {
   if (passedinstring.includes(filterstrings[i].toLowerCase())) {
       alert("string detected");
   }
}

Solution 5 - Javascript

You can switch .includes with the .some method which returns a boolean.
It will exit as soon as a match was found, which is great for performance for huge arrays:

.some(item => item.toLowerCase() == lookup.toLowerCase())
Demo:

var arr = ['foo','bar','bar'];
var lookup = "bAr";

// case-sensetive
console.log( arr.includes(lookup) )

// case-insensetive without caring about the type
console.log( arr.some(x => x.toLowerCase() == lookup.toLowerCase()) ) 


Or define your own Array prototype method with a unique name:

// the name ("_includes") should be unique enough not to ever be overriten 
// by future language updates or 3rd-party scripts
Array.prototype._includes = function(target){ 
  return this.some(x => x.toLowerCase() == (target||'').toLowerCase()) 
}

console.log( 
  ['foo', 'bar', 'bar']._includes("bAr") 
)

Solution 6 - Javascript

Fixed case sensitivity issue using toLowerCase(). It turns all the string to lower case while comparing.

var product=productList.filter((x) => x.Name.toLowerCase().includes(("Active").toLowerCase()))

Solution 7 - Javascript

My option is comparing UPPER with UPPER or lower with lower transforming both sides (i did it often in SQL):

    var filterstrings = ['firststring','secondstring','thirDstrIng'];
    var passedinstring =  'ThIrDsTrInG3';
    
    //used for of just to make it more readable
    for (filterstring of filterstrings) {
        if (passedinstring.toUpperCase().includes(filterstring.toUpperCase())) {
            alert("string detected");
        }
    
    }

Prompts string detected

Solution 8 - Javascript

var filterstrings = ['firststring','secondstring','thridstring'];
var passedinstring = localStorage.getItem("passedinstring");

filterstrings.filter(item => item.name.toLowerCase().includes(passedinstring.toLowerCase()))

Solution 9 - Javascript

I believe this would be simpler, shorter and more understandable.

  const q = new RegExp(query, 'i');

  filteredUsers = users.filter((user: User) => {
    return (
      user.entity.short.match(q) ||
      user.firstname.match(q) ||
      user.lastname.match(q)
    );
  });

Solution 10 - Javascript

You can try this.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
string = fruits.join(' ').toUpperCase();
// Output"BANANA ORANGE APPLE MANGO"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLegendDemonSlayerView Question on Stackoverflow
Solution 1 - Javascriptgurvinder372View Answer on Stackoverflow
Solution 2 - JavascriptNabin PaudyalView Answer on Stackoverflow
Solution 3 - JavascriptKamran KhattiView Answer on Stackoverflow
Solution 4 - JavascriptSaurabh MistryView Answer on Stackoverflow
Solution 5 - JavascriptvsyncView Answer on Stackoverflow
Solution 6 - JavascriptR15View Answer on Stackoverflow
Solution 7 - JavascriptDDSView Answer on Stackoverflow
Solution 8 - JavascriptRAVI PRATAP SINGH RPSView Answer on Stackoverflow
Solution 9 - JavascriptMianala LoharanoView Answer on Stackoverflow
Solution 10 - JavascriptShantesh SindgiView Answer on Stackoverflow