I encountered a problem in project development
I need to use regular expressions, replace, and template strings to process a string.
I found a strange problem, but I couldn’t explain it myself. I made a simple demo and you can see why using different single and double quotation marks can result in different results
const params = '123$';
const aa = `test(input)`;
const res1 = aa.replace(/input/g, `'${params}'`);
const res2 = aa.replace(/input/g, `"${params}"`);
console.log(res1); // test('123))
console.log(res2); // test("123$")
My native language is not English, so there are some grammar issues, but I can use a translator to communicate with you,thank you!
that is a issue,hava nothing to do
2
Answers
you can modify like this
const params = "123$$";
const aa = "test(input)";
const res1 = aa.replace(/input/g, params);
$'
has a special meaning in a regex replacement string. The easiest way to work around that is to not pass a replacement string toreplace
, but a callback function. The return of this callback function will be used literally as is without any further interpretation of special characters: