-1

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

4
  • 2
    When building a regex from a string literal, the \ 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"); Commented Sep 15, 2014 at 17:44
  • @cookiemonster if i run the code you mentioned, it shows name is not defined. Commented Sep 15, 2014 at 17:54
  • @AvinashRaj: Then you obviously didn't define a variable name. Commented Sep 15, 2014 at 19:08
  • @AvinashRaj typo, sorry. Fixed. Commented Sep 15, 2014 at 21:34

2 Answers 2

1

You missed the escapes. Replace this:

new RegExp("\{\{\s*"+name+"\s*\}\}", "g");

With this:

new RegExp("\\{\\{\\s*"+name+"\\s*\\}\\}", "g");

You have to double escape the backslashes, once for the JS string, and once for the regex.

That's the reason behind the regex literal /.../ which you can't use here... Or, perhaps you could:

var regex = /\{\{\s*(\w+)\s*\}\}/g;

Capture everything, and filter out the results afterwards. The name is in the first captured group.

string.replace(regex, function(m, name) {
    return "whatever " + name; 
});
Sign up to request clarification or add additional context in comments.

Comments

0

Your code would be,

> var keyName = "name";
> var regex = new RegExp("\\{\\{\\s*"+keyName+"\\s*\\}\\}", "g");
undefined
> var string = "Howdy, my name is {{  name}}";
undefined
> string.replace(regex, "Chris")
'Howdy, my name is Chris'

You need to include the variable which stores the value name in the RegExp pattern and also you need to escape \ one more time because the pattern was included within double quotes .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.