If Statement

Hopefully this will be an easy one. I want to write an IF statement to determine if a field contains a certain value. I have a field that users have populated with data using checkboxes on a form, so, for example the field “colors” = Blue Red Orange. My code looks something like this:

if (colors == "Blue")
{
     //do something
}

But this only returns true if ONLY blue is selected. How can I determine if this field “contains” blue regardless of what other colors may be selected. I tried this to no avail:

if (colors == "%" + "Blue" + "%")
{
     //do something
}

thank you.

if (colors && (colors.toLowerCase().indexOf('blue') > -1)) {
    // do something
}

Thank you Patrick

I had a similar problem searching Tickbox data and completely overlooked ‘indexOf’. Your suggestion is sooo much more elegant than my clunky workaround :)

Cheers

Of course

if (colors && colors.match(/blue/i)) {
    // do something
}

is even more elegant…

Well I never new that!

"The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object.

Perform a global, case-insensitive search for "ain":

var str = "The rain in SPAIN stays mainly in the plain"; 
var res = str.match(/ain/gi);
The result of res will be:

ain,AIN,ain,ain

Thanks guys.

m.vanklink:
match

Even more elegant would be to use test instead of match:

if (colors && /blue/i.test(colors)) {
    // do something
}

The test function doesn’t get all matches, so it is faster.

Performance difference is substantial (at least in my browser)!

http://jsperf.com/regexp-test-vs-match-m5