Need to loop an array of strings and check against with another string, which is passed in the 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 it's case insensitive(preferably by using regex) when filtering, if the var passedinstring
were to have strings like FirsTsTriNg
or fiRSTStrING
?
You can create a RegExp from filterstrings
first
var filterstrings = ['firststring','secondstring','thirdstring'];
var regex = new RegExp( filterstrings.join( "|" ), "i");
then test
if the passedinstring
is there
var isAvailable = regex.test( passedinstring );
Here is a test implementation:
// Take care to escape these strings!
// If they are user-input or may contain special regex characters (such as "$" or "."), they have to be escaped.
var filterStrings = ['one','two','three'];
var regex = new RegExp(filterStrings.join( "|" ), "i");
var sentences = [
"one", // true
"OnE", // true
"a rabbit", // false
"and then two rabbits", // true
"standing", // false
"prone", // true
"AoNeAtWo", // true
];
sentences.forEach(sentence => {
console.log(
regex.test(sentence) ? '✅ match:' : '❌ not a match:',
"'" + sentence + "'",
);
});