Donny van V Donny van V - 16 days ago 5
Javascript Question

Javascript string in array or a part - [Solved with solution]

I have a Javascript array with multiple values:

var filterClasses = ['col-sm-12', 'hidden-xs', 'hidden-sm', 'hidden-lg', 'hidden-md', 'active', 'btn-'];


I have a function that gets all css classes in the DOM. But i want to check if this class should be added to a new array or not. So i can use indexOf for this:

return filterClasses.indexOf('col-sm-12');


This returns a true, so this class should be ignored.

But now i have a class that is btn-primary. As you see in my array i have the
btn-
added in it. I want to exclude all classes that contains the word
btn-
. How can i achieve this?

Current function:

function setupShouldAddClass( cssClass, filterClasses )
{
// If the cssClass exists in the filterClasses then false
if ( filterClasses.indexOf(cssClass) > 0 )
{
return true;
}

filterClasses.forEach(function ( item )
{
if ( stringContains(item, cssClass) )
{
return true;
}
});

return false;
}

function stringContains( needle, haystack )
{
return (haystack.indexOf(needle) !== -1);
}

Answer

Maybe you can solve your issue using regular expressions instead of using imperative code:

var classBlackListRegExp = /(col-sm-12|hidden-xs|hidden-sm|hidden-lg|hidden-md|active|^btn-.+)/i;

var result = classBlackListRegExp.test("btn-whatever");

console.log(result);

Check the ^btn-.+ part. This matches anything starting with "btn-".

I believe that your scenario is the ideal use case of regular expressions!

OP concerns if class black list is very large

OP said:

what im wondering is, that if i add more then 100 classes, how does this handle the line breaks?

You can join the whole array of black-listed strings and create a RegExp object with it as follows:

// I use a templated string and String.prototype.join
// to create a regular expression from a given array:
var classBlackListRegExp = new RegExp(`(${[
  'col-sm-12', 
  'hidden-xs', 
  'hidden-sm', 
  'hidden-lg', 
  'hidden-md', 
  'active', 
  '^btn-.+'
].join("|")})`, "i");

var result = classBlackListRegExp.test("btn-whatever");

console.log(result);