This does not work because of the variable rep. What is the correct syntax please?
var bigtext = 'testing test test test';
var rep = 'test';
bigtext = bigtext.replace(/rep/g, "MOO!");
I know the problem is with the regex part in the replace…but what is the correct way to write it?
You need to build a regex using the
RegExpconstructor:Documentation for this constructor can be seen on the MDN page. Note that you probably should make sure that any special characters in regular expressions (e.g.
[) are escaped.