Member-only story

Unlock the Power of Raw Strings in JavaScript with Tagged Template Literals

Say goodbye to escaped characters and hello to greater flexibility in your string manipulation

Max N
3 min readApr 1, 2024

Tagged template literals are a feature introduced in ECMAScript 2015 (ES6) that allow you to apply custom functionality to template literal strings. When used properly, tagged template literals can provide enhanced control over how strings are parsed and evaluated, including the ability to access raw string values.

By default, template literals will automatically escape certain characters, such as newline characters (\n), tab characters (\t), and quote marks (“ or ‘) within the string. However, there may be times when you want to preserve these special characters rather than having them interpreted by the JavaScript engine. That’s where raw strings come in.

To create a raw string using a tagged template literal, simply include an additional function call before the template literal expression, followed by a set of parentheses containing the raw string value. Here’s an example:

function htmlEscape(strings, ...values) {
let output = '';
strings.forEach((string, i) => {
if (i > 0) {
output += values[i - 1];
}
output += string.raw ? string.raw : string;
});
return…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet