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:
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"