0

I would like to combine these JavaScript regex's into a single regex. How can I do this? I have tried using the '|' operator in-between strings, but this does not work.

var r1 = new RegExp(id + '\\s*===\\s*TRUE', 'gm');
var r2 = new RegExp(id + '\\s*===\\s*true', 'gm');
var r3 = new RegExp(id + '\\s*===\\s*FALSE', 'gm');
var r4 = new RegExp(id + '\\s*===\\s*false', 'gm');
var r5 = new RegExp(id + '\\s*!==\\s*TRUE', 'gm');
var r6 = new RegExp(id + '\\s*!==\\s*true', 'gm');
var r7 = new RegExp(id + '\\s*!==\\s*FALSE', 'gm');
var r8 = new RegExp(id + '\\s*!==\\s*false', 'gm');

2 Answers 2

1

Try this:

var r = new RegExp(id+"\\s*[!=]==\\s*(?:true|false)","gi");

I removed the m modifier, since it doesn't apply here, and added the i modifier to take care of all case options.

Sign up to request clarification or add additional context in comments.

2 Comments

How come you remove the extra escape on the "\s". When I use your regex I no longer match strings like "DEF === TRUE". Is there something I don't know here?
@Kolink: I edited your answer to include an escape to the ``.
0

In this specific case

new RegExp(id + '\\s*[!=]==\\s*(?:TRUE|true|false|FALSE)', 'gm')

should do the trick.

In the general case, joining the strings with '|' should work.

@Kolink's answer is better if you also want to accept 'fAlSe' and similar strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.