6

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

Jack M.
  • 3,676
  • 5
  • 25
  • 36
  • 1
    possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – Leonid Beschastny Aug 15 '14 at 17:11
  • The question is different, the answer is similar, but thanks anyway I missed that topic. – Jack M. Aug 15 '14 at 17:34

2 Answers2

11

You can use new RegExp()

var newString = phrase.replace(new RegExp(find, 'g'), replace);
Paul
  • 139,544
  • 27
  • 275
  • 264
monkeyinsight
  • 4,719
  • 1
  • 20
  • 28
4

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')
Community
  • 1
  • 1
Paul
  • 139,544
  • 27
  • 275
  • 264