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?

3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This works thanks! and also thanks for the link to more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.