Paul Kruger
Paul Kruger

Reputation: 2304

Regex expression using ${}

I can't get this regex to work:

let varString = 'I am writing a ${varHere}';
let myKey = 'varHere';

pString = pString.replace(new RegExp(`\${${myKey}}`, 'g'), 'test');

But this works:

let varString = 'I am writing a ${varHere}';
let myKey = 'varHere';

pString = pString.replace(new RegExp(`{${myKey}}`, 'g'), 'test');
// pString = 'I am writing a $test';

It is just the $ that is a problem.

Upvotes: 0

Views: 218

Answers (1)

Christoph Herold
Christoph Herold

Reputation: 1809

You are not interpolating your string correctly:

console.log(`\$\{${myKey}\}`);

will get you ${varHere}. Putting this in the RegExp, it will try to match $ (End of line) for {varhere} number of times, which is, of course, an invalid regular expression. You need to escape your expression to get the desired result:

new RegExp(`\\\$\\\{${myKey}\\\}`, 'g')

Instead, since you're not really in need of a RegExp here, you could also use the simpler string replace:

pString = varString.replace(`\$\{${myKey}\}`, 'test');

Upvotes: 3

Related Questions