Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape a backtick in a JavaScript raw string?

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.
like image 597
Arjun Avatar asked Mar 12 '26 03:03

Arjun


1 Answers

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);
like image 54
Arjun Avatar answered Mar 13 '26 15:03

Arjun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!