开发者

Check if var has "cheese" OR "cake" in it?

开发者 https://www.devze.com 2022-12-10 10:05 出处:网络
How can I check if a variable has something in it? I tried checking if a .match() returned null but that wasn\'t useful 开发者_StackOverflow社区for checking with an OR?/cheese|cake/.test(a)

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


/cheese|cake/.test(a)

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


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;


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消