0

This almost has the answer... How do you use a variable in a regular expression?

I need to know if I can use variables instead of hardcode in the regex?

str1 = str1.replace(/abcdef/g, "stuvwxyz");

can I use variables instead of /abcdef/g and "stuvwxyz"

Community
  • 1
  • 1
gravityboy
  • 817
  • 5
  • 11
  • 21

3 Answers3

7

Of course that you can, every single bit of this can be dynamic:

var pattern = 'abcdef';
var input = 'stuvwxyz';
var modifiers = 'g';
var regex = new RegExp(pattern, modifiers);
var str1 = 'Hello abcdef';
str1 = str1.replace(regex, input);

Checkout the docs as well.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Is there any reason to use new here? – kennebec Jun 20 '11 at 22:19
  • @kennebec, you may checkout the following thread about the `new` keyword in javascript: http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful – Darin Dimitrov Jun 20 '11 at 22:21
  • These answers are all just about the same (or were, you did some fast editing) but you were first. – gravityboy Jun 20 '11 at 22:23
  • 1
    Other answers don't mention how to make the regex dynamic, just the string to be searched and the what to replace it with. – Ruan Mendes Jun 20 '11 at 22:45
  • @juan-mendes yes juan... that is why I said "or were" he edited really fast... he is good. His initial answer was just like the rest. – gravityboy Jun 21 '11 at 00:31
1

Yes.

var pattern = /abcdef/g;
var input = "stuvwxyz";
str1 = str1.replace(pattern, input);
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
1

Like this?

var regex = /abcdef/g;
var string = "stuvwxyz";
var str1 = "abcdef";
str1 = str1.replace(regex, string);
TomHastjarjanto
  • 5,386
  • 1
  • 29
  • 41