Template literals with nested backticks(`) in ES6

前端 未结 8 980
离开以前
离开以前 2020-12-03 04:23

How can I write a template literal in ECMAScript 6 that will contain backticks(`) in and by itself, (i.e. nested backticks)?

For example:

var qu         


        
相关标签:
8条回答
  • 2020-12-03 05:08

    As mentioned in other answers, you can escape the backtick ` with a backslash, like \`.

    var tripleBacktickExample = `
    \`\`\`python
    # This JavaScript string contains some example Markdown that
    # uses triple-backticks to delimit a Python code block.
    \`\`\`
    `
    

    However, if you need very many backticks in a row ````` inside the template literal, it could be more readable to put them within a normal string that is inside a placeholder, like ${'`````'} or ${"`````"}.

    var tripleBacktickExample = `
    ${'```'}python
    # This JavaScript string contains some example Markdown that
    # uses triple-backticks to delimit a Python code block.
    ${'```'}
    `
    
    0 讨论(0)
  • 2020-12-03 05:15

    To escape all special characters, not just the backticks:

    let str = '`Hello`\\n${world}';
    let escacped = str.replace(/\\|`|\$/g, '\\$&');
    console.log(eval('`' + escaped + '`') === str); // test
    

    I needed this for some code generation stuff. The str was the content of a JavaScript file and the goal was to put this content into a string literal variable into another generated JavaScript file.

    Sadly it seems there is (2019) no native JavaScript function for this escaping. The characters that needs to be replaced are: `, \, $ and \.

    0 讨论(0)
提交回复
热议问题