user2272048
user2272048

Reputation:

How can I use a variable inside a RegEx (Javascript)?

I already looked at the Mozzila website and W3schools but couldn't find the answer

var someFunction = function (someString, someOtherString)
{
   if (someOtherString.match(someString))
   {
     someString = new RegExp(someString);
     someOtherString = someOtherString.replace(someString, "XXX");
     return someOtherString;
   }

   return null;
};

someFunction("dog", "dogeatdog");

Now I want the above RegExp to be applied globally but I don't know where/how to add the g character so that the above function call returns XXXeatXXX.

Any help would be appreciated!

Upvotes: 0

Views: 29

Answers (1)

Phil
Phil

Reputation: 165069

Flags go in the second argument of the RegExp constructor, eg

new RegExp(someString, 'g')

Upvotes: 1

Related Questions