String.raw() in JavaScript

JavaScript's String.raw() is a built-in method that provides a way to work with template literals in their raw form. We use String.raw() to interpret a template literally exactly as it is typed, without processing escape sequences like \n or \t.

String.raw() can be used directly with template literals to capture raw strings. Here’s how:

const rawString = String.raw`Hello\nWorld!`;
console.log(rawString); // Output: "Hello\\nWorld!"

In this example, the output retains the backslash (\) found in the escape sequence, treating it as a literal character.

Pitfalls

While using String.raw(), the first argument requires a valid raw property. Failing to do so results in a TypeError:

try {
    const result = String.raw({}); // This will fail
} catch (e) {
    console.log(e.message); // TypeError: Cannot convert undefined or null to object
}

String.raw() is a great JavaScript utility for handling raw strings. It is especially useful when working with file paths, regular expressions, or wherever your escape sequences should not be processed as special characters.

It's got me out of a few headaches, so it's definitely a good one to remember in your JavaScript toolkit. ❤️

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.