0

Sometimes I need to use regex with g and sometimes without g.

let setreg = /set (\w+) (.+?)/g;
let setregnog = /set (\w+) (.+?)/;

Is there a way to just add a g to the end of setreg instead of using 2 vars.

Harry
  • 52,711
  • 71
  • 177
  • 261
  • Does this answer your question? [Adding modifiers to an existing regular expression](https://stackoverflow.com/questions/9437203/adding-modifiers-to-an-existing-regular-expression) – shkaper Feb 22 '20 at 15:52

1 Answers1

0

Yes - you can use the RegExp() constructor.

let ptn = /foo/;
new RegExp(ptn, 'g'); //<-- with
new RegExp(ptn); //<-- without
Mitya
  • 33,629
  • 9
  • 60
  • 107