Ad

Regular Expression && || Conundrum

- 1 answer

I would greatly appreciate if someone can please explain why this is. The attached images show a console shot of a Javascript Regular Expression that I was trying after I followed the lesson in conjunction. I was expecting to get all true booleans when using the OR || operator, at least.

regular expression with || operator:

regular expression with || operator

regular expression with && operator:

regular expression with && operator

Ad

Answer

A RegExp will always evaluate to true, so according to the logical operator rules:

(/Mou/) || (/str/)  //=> /Mou/

and

(/Mou/) && (/str/)  //=> /str/

document.write( (/Mou/) || (/str/));

document.write('<br>');

document.write( (/Mou/) && (/str/) );

If what you want to test is the presence of either "Mou"OR"str" in a string then you can use this RegExp which uses the pipe symbol to achieve logical or behavior withing a group (more info):

/(Mou|str)/

// or dynamically constructed:
var a = "Mou";
var b = "str";
var regexp = new RegExp('('+a+'|'+b+')');

If what you want to test is the presence of both "Mou"AND"str" then you can use this slightly more complicated construct, which makes use of positive lookaheads (more info):

/(?=.*Mou)(?=.*str)/

// or dynamically constructed:
var a = "Mou";
var b = "str";
var regexp = new RegExp('(?=.*'+a+')(?=.*'+b+')');
Ad
source: stackoverflow.com
Ad