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