0
var s="Fred";
_.replace('Hi Fred', s, 'Barney');

Result : "Hi Barney"

I want to know how to use replace function when regex pattern is stored in a variable.

var s="Fred";
_.replace('Hi Fred', /s/, 'Barney');

Result : "Hi Fred"
Soumya dutta
  • 79
  • 1
  • 7

1 Answers1

0

This question isn't specific to lodash, really. You just need to create the regex with the RegExp constructor instead of the literal syntax:

var s="Fred";
var r=new RegExp(s);
var result = _.replace('Hi Fred', r, 'Barney');

console.log(result);
// "Hi Barney"

Check here for more help:

How do you use a variable in a regular expression?

sripberger
  • 1,382
  • 1
  • 5
  • 18