7

I have a raw string (created with the String.raw method and template literal), which is supposed to contain several backslashes and backticks. Since the backticks are required to be escaped even in a raw string, I use backward slashes to escape them. Although, it does escape the backtick, the backward slash is also displayed along with it:

let rawString = String.raw`
  __    
 /  |   
 \`| |   
  | |   
 _| |_  
|_____| 


`;

console.log(rawString);
  • How do I escape the backtick such that there is no extra backward slash preceding it?

Some Clarifications

  • The string is required to be a raw string.
  • The backticks are necessary. They can't be replaced with single quotes or anything like that.
Community
  • 1
  • 1
Arjun
  • 1,261
  • 1
  • 11
  • 26

2 Answers2

8

So, while writing the question, I came up with an idea myself, and to my utmost surprise - it works!


Instead of using the backward slash for escaping, use ${...} ("placeholder" for string interpolation); like this:

let rawString = String.raw`
  __    
 /  |   
 ${"`"}| |   
  | |   
 _| |_  
|_____| 


`;

console.log(rawString);
Arjun
  • 1,261
  • 1
  • 11
  • 26
2

var v='`';
let rawString = String.raw`
      __    
     /  |   
     `+v+`| |
      | |   
     _| |_  
    |_____| 


`;

//From seeing from your idea, you can join it like below:

console.log(rawString);
rawString = String.raw`
      __    
     /  |   
     ${v}| |
      | |   
     _| |_  
    |_____| 


`;

console.log(rawString);
Jovylle
  • 859
  • 7
  • 17
  • That doesn't answer the question because I have very clearly stated in the question that the raw string contains several backticks. – Arjun Jun 19 '20 at 04:50
  • I suggest you delete your answer or update it to comply with the question. Thank you for trying to help though! – Arjun Jun 19 '20 at 04:55
  • I have updated this, the other answer will be a lot cleaner, which was also yours – Jovylle Jun 19 '20 at 04:59