Javascript:替换字符串中带标签的模板文字

时间:2019-03-19 11:05:41

标签: javascript

我有包含以下内容的字符串:

const string = `describe('Test', () => {
  it('found', async () => {
    await createUser();
    const test = await agent.get(`${prefix}/test`)
  });
  it('array', async () => {
    await createUser();
    const test = await agent.get(`${prefix}/test`)
  });
});`

当我尝试控制台记录此字符串时,我得到${prefix}Unexpected identifier,而当我尝试将其替换为其他内容时,也会遇到相同的错误。

3 个答案:

答案 0 :(得分:0)

在字符串的不同部分之间使用串联:

const string = `describe('Test', () => {
  it('found', async () => {
    await createUser();
    const test = await agent.get(`+`${prefix}/test`+`)
  });
  it('array', async () => {
    await createUser();
    const test = await agent.get(`+`${prefix}/test`+`)
  });
});`

答案 1 :(得分:0)

您不需要在字符串内反引号。

const string = `describe('Test', () => {
  it('found', async () => {
    await createUser();
    const test = await agent.get(${prefix}/test)
  });
  it('array', async () => {
    await createUser();
    const test = await agent.get(${prefix}/test)
  });
});`

答案 2 :(得分:0)

添加引号:

const string = `describe('Test', () => {
  it('found', async () => {
    await createUser();
    const test = await agent.get('${prefix}/test')
  });
  it('array', async () => {
    await createUser();
    const test = await agent.get('${prefix}/test')
  });
});`
相关问题