How to show the strings in raw format using the String.raw template literals tag function in JavaScript?

Published January 22, 2021

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 \n (newline) like this anywhere in the string, so that when the JavaScript engine executes the code it will move the string to a new line where it is encountered.

// 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.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter