0

How do I replace "$id" with a value? I need to replace the regular expression in the sql string with a value. I'm trying to use RegExp.

const src = "SELECT * FROM users WHERE id=$id";
const myFind = "$id";
// $id is the property of the object. example { $id: 123,}
const find = new RegExp(myFind, 'g');
const repl = 123;

const _completeSQL = src.replace( find, repl);
console.log(`_completeSQL ${_completeSQL}`);

My attempt fails because $ is a regular expression.

1 Answers1

0

Like @CertainPerformance has said, you need to use a backslash to escape $ in a regular expression. You should also use \b to match a word boundary so that other words starting with id won't match. In other words, you should do:

const myFind = "\\$id\\b";

or:

const myFind = /\$id\b/;

Note that if you choose to use double-quotes to enclose your regular expression, you will need to use double-backslashes to denote one backslash, so that what follows the backslash can be properly escaped when evaluated as a regular expression.

blhsing
  • 91,368
  • 6
  • 71
  • 106