A couple js regex questions

I am quite a novice at javascript, but I do have gained an understanding of OOP from PHP.

I have seen RegExp() object being used in some script… BUT I also have seen this being used instead: cls=/ain/gi;

What is the advantage of using an object instead of a simple variable as above?

and at the risk of answering my own question, is there a way to use a variable INSIDE a regex expression when NOT using the RegExp() object?
something like this…

VariableHere=“some_sting”;
cls=/(\s|^)VariableHere(\s|$)/gi;

As always … advice is appreciated and thanks in advance

Using the RegExp constructor creates the same object as using the [url=“https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions”]regular expression literal. The literal form is the preferred technique. Use the RegExp constructor only when the pattern may be variable, or when it’s provided from an external source.

Not unless you want mobs of people screaming “eval is evil!!!” in your ear.

You’ll need the RegExp constructor for that.

When using the constructor, since normal string escape rules apply, you’ll also need to escape occurrences of the backslash.


cls = new RegExp('(\\\\s|^)' + VariableHere + '(\\\\s|$)', 'gi');

Thanks Paul! I think I get it now.