I'm well aware of the standard approach of using the RegExp object to match dynamic variables in JavaScript. However I'm having some difficulty with whitespacing.
The aim is that there can be 0 or more white spaces in between {{ or }}, and the dynamic variable name.
The behaviour I'm trying to mirror
var regex = /\{\{\s*name\s*\}\}/g;
var string = "Howdy, my name is {{ name}}";
string.replace(regex, "Chris")
// => "Howdy, my name is Chris"
My current code
var keyName = "name";
var regex = new RegExp("\{\{\s*"+keyName+"\s*\}\}", "g");
var string = "Howdy, my name is {{ name}}";
string.replace(regex, "Chris")
// => "Howdy, my name is {{ name}}"
Am I missing something? Thanks
\is interpreted as the start of an escape sequence of that string literal, and so it never makes it into the regex. To include a literal\character in a string, you need to escape it\\. So...new RegExp("\\{\\{\\s*"+name+"\\s*\\}\\}", "g");nameis not defined.name.