Skip to content Skip to sidebar Skip to footer

Simple Way To Use Variables In Regex

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

Solution 1:

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

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

Checkout the docs as well.

Solution 2:

Yes.

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

Solution 3:

Like this?

var regex = /abcdef/g;
varstring = "stuvwxyz";
var str1 = "abcdef";
str1 = str1.replace(regex, string);

Post a Comment for "Simple Way To Use Variables In Regex"