How to I incorporate find
variable, within a Regex ?
var find = 'de';
var phrase = 'abcdefgh';
var replace = '45';
var newString = phrase.replace(/de/g, replace)
i.e.: var newString = phrase.replace(/find
/g, replace)
expected: phrase = 'abc45fgh';
You can use new RegExp()
var newString = phrase.replace(new RegExp(find, 'g'), replace);
monkeyinsight's answer is great, but there is something else you should know. You need to be careful, depending on how find
is constructed. Suppose that you have something like:
var name = 'Paul Oldridge (paulpro)';
var find = '/foo/(' + name + ')/bar';
Then you need to decide if you want to escape it for regex, so that it matches exactly the string /foo/Paul Oldridge (paulpro)/bar
or if you want it to evaluate name
as a regular expression itself, in which case (paulpro)
would be treated as a capturing group and it would match the string /foo/Paul Oldridge paulpro/bar
without the parenthesis around paulpro
.
There are many cases where you might want to embed a subexpression, but more commonly you want to match the string exactly as given. In that case you can escape the string for regex. In node you can install the module regex-quote
using npm. You would use it like this:
var regexp_quote = require("regexp-quote");
var name = 'Paul Oldridge (paulpro)';
var find = '/foo/(' + regexp_quote( name ) + ')/bar';
Which would correctly escape the parenthesis, so that find
becomes:
'/foo/(Paul Oldridge \(paulpro\))/bar'
and you would pass that to the RegExp constructor as monkeyinsight showed:
new RegExp(find, 'g')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With