Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS variable with in Regex expression

Tags:

node.js

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';

like image 740
Jack M. Avatar asked Aug 15 '14 16:08

Jack M.


2 Answers

You can use new RegExp()

var newString = phrase.replace(new RegExp(find, 'g'), replace);
like image 187
monkeyinsight Avatar answered Nov 09 '22 04:11

monkeyinsight


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')
like image 4
Paul Avatar answered Nov 09 '22 05:11

Paul