DEV Community

Codecupdev
Codecupdev

Posted on

What is String.raw() in JavaScript?

A video of this article is available below:

Introduction

In this article, I will be introducing raw strings in JavaScript.

Sometimes when we work with template literals we use them to convert characters. Let’s clarify this with an example.

console.log(`Monday\nTuesday\nWednesday`);
//Returns --->
Monday
Tuesday
Wednesday
Enter fullscreen mode Exit fullscreen mode

In the above example we console log a template literal or a template string which contains Monday, Tuesday and Wednesday each separated with the newline character. When this runs each of the words is printed on a new line.

String.raw()

JavaScript provides us with the String.raw() tag function which enables us to access the raw string from a template literal. This means we are able to access the string where the escape characters are not processed. Let’s expand on the above example with this.

String.raw`Monday\nTuesday\nWednesday`;
//Returns ---> 'Monday\nTuesday\nWednesday'
Enter fullscreen mode Exit fullscreen mode

In the above example we use the String.raw() method and pass the template literal as the parameter. We get the same string returned without the newline characters processed.

Interpolation

When you use the raw method anything interpolated into the string will be processed. Let’s look at an example of this.


console.log(`Sum: ${4+5}`);
//Returns ---> Sum: 9
Enter fullscreen mode Exit fullscreen mode

In the above example inside of a console log we use string interpolation to sum 4 and 5. We get the string with the sum returned. Now let’s try doing this with the raw method.

String.raw`Sum: ${4+5}`;
//Returns ---> 'Sum: 9'
Enter fullscreen mode Exit fullscreen mode

In the above example we use the raw method and pass in the template literal with the interpolated sum. We get the returned string with the completed sum because anything we pass in to be interpolated does get processed by the method.

Unicode

Another time that the raw string method is useful is if you are using unicode characters.

console.log(`\u2605`);
//Returns ---> ★
Enter fullscreen mode Exit fullscreen mode

In the above example, we use the Unicode character to access a star symbol and this is returned to us. Now let's use the raw method on this template literal.

String.raw`\u2605`;
//Returns ---> '\\u2605'
Enter fullscreen mode Exit fullscreen mode

We go on to use the raw method passing in the Unicode character. Nothing is processed and we get the raw string returned.

I hope you enjoyed this article. Please feel free to post any comments, questions, or feedback, and follow me for more content!

Top comments (0)