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?
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?
Share Improve this question edited Aug 14, 2012 at 14:19 olly_uk 11.9k3 gold badges41 silver badges45 bronze badges asked Aug 14, 2012 at 14:15 David19801David19801 11.4k26 gold badges86 silver badges127 bronze badges 3- possible duplicate of Using a string variable as regular expression and Pass a variable into regex with string replace. – Felix Kling Commented Aug 14, 2012 at 14:18
- And what has jQuery got to do with basic regular expressions? – epascarello Commented Aug 14, 2012 at 14:18
- @David: epascarello's point was that this has nothing to do with jQuery. Regular expressions are a feature of the language itself. – Felix Kling Commented Aug 14, 2012 at 14:21
1 Answer
Reset to default 7You need to build a regex using the RegExp
constructor:
var bigtext = 'testing test test test';
var rep = 'test';
var regex = new RegExp(rep, 'g');
bigtext = bigtext.replace(regex, "MOO!");
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.