Search code examples
javascriptstring-interpolation

Elegant way to add a pair of back ticks to the resulting string from javascript string interpolation?


I'm using string interpolation to create a string that I am sending to another service. This other service allows for back ticks to format text when it is displayed. I would like to include back ticks in this string so that it is more readable to the end user.

I found a way, but it seems sloppy. It takes me 6 characters to add 1 character to my output, and sends my pinkies all over the keyboard, making it difficult to type:

const myString = `There will be one here -> ${'`'} and one here -> ${'`'}.`;
// There will be one here -> ` and one here -> `.

Is there a better way I could do this?


Solution

  • You can use backslashes to escape them:

    To escape a back-tick in a template literal, put a backslash \ before the back-tick. - MDN

    const myString = `There will be one here -> ${'`'} and one here -> ${'`'}.`;
    const myString2 = `There will be one here -> \` and one here -> \`.`;
    
    console.log(myString === myString2);