skip to Main Content

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


  1. you can modify like this

    const params = "123$$";

    const aa = "test(input)";

    const res1 = aa.replace(/input/g, params);

    Login or Signup to reply.
  2. $' has a special meaning in a regex replacement string. The easiest way to work around that is to not pass a replacement string to replace, but a callback function. The return of this callback function will be used literally as is without any further interpretation of special characters:

    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$")
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search