Question

How can I check if a variable has something in it? I tried checking if a .match() returned null but that wasn't useful for checking with an OR?

Was it helpful?

Solution

As you only got answers involving regular expressions, here is the plain string operation solution:

var hasMatch = input.indexOf('cheese') != -1 || input.indexOf('cake') != -1;

OTHER TIPS

/cheese|cake/.test(a)

you could add an i at the end of the regex if you want to test case-insensitively

Try this:

var myString = 'I love cheese';
var isMatch = new RegExp(/(cheese|cake)/i).test(myString); //should return true

all expressions posted so far would also match "cheeseburger" and "cakewalk". Don't know if this is desirable or not, just in case here's the version that doesn't:

alert(/\b(cheese|cake)\b/i.test("cheese and cake")) // true
alert(/\b(cheese|cake)\b/i.test("cheeseburger and pancake")) // false

Don't you just want the following?

var result = input.match("cheese") || input.match("cake");
var matched = !!('cheese'.match(/(?:cheese|cake)/g));
alert(matched)

Or RegExp.prototype.test:

var matched = /cheese|cake/i.test('cheese cake');
alert(matched)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top