Adam Adam - 1 year ago 114
Javascript Question

Javascript Regex: How to put a variable inside a regular expression?

So for example:

var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")

But this is of course not working :)
Is there any way to do this?

Answer Source
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
string.replace(regex, "replacement");


Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download