繁体   English   中英

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

[英]Javascript: replace tagged template literals in string

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

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 ,当我尝试将其替换为其他内容时,遇到相同的错误。

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

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`+`)
  });
});`

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

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)
  });
});`

添加引号:

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')
  });
});`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM