2

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?

olly_uk
  • 11,559
  • 3
  • 39
  • 45
David19801
  • 11,214
  • 25
  • 84
  • 127
  • possible duplicate of [Using a string variable as regular expression](http://stackoverflow.com/questions/4786996/using-a-string-variable-as-regular-expression) and [Pass a variable into regex with string replace](http://stackoverflow.com/questions/3139563/pass-a-variable-into-regex-with-string-replace?rq=1). – Felix Kling Aug 14 '12 at 14:18
  • And what has jQuery got to do with basic regular expressions? – epascarello Aug 14 '12 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 Aug 14 '12 at 14:21

1 Answers1

7

You 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.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318