Consider a scenario where you have a simple normal string like this,
// Simple String const simpleString = "Hey, I'm a simple string!"; // OUTPUT: "Hey, I'm a simple string!"
Nothing fancy at all. The output will be shown in the same line.
Now if you add an escape character
// Simple string with a newline escape character const simpleString = "Hey,\n I'm a simple string!"; // OUTPUT: // "Hey, // I'm a simple string!"
Here the string is in a new line.
What if we don't' want this to happen and need to show the escape character
\n too in the output.
For that, we have something called the
String.raw tag function of template literals.
We can wrap the above string in template literals tag function
String.raw like this,
// Simple string with a newline escape character // But wrapped in String.raw tag function const simpleString = String.raw`Hey,\n I'm a simple string!`; // OUTPUT: // "Hey,\n I'm a simple string!"
Now the output will also contain the escape characters as we wrote in the string. The
String.raw tag function ignores all kinds of escape characters and uses the string in its raw format without adding or doing any formatting in the string.
See these examples live in JSBin.