Raw Strings with String.raw
You'll learn how to access the literal characters in a template literal without JavaScript processing escape sequences.
What Are Raw Strings?
Normally, JavaScript interprets escape sequences like \n (newline) or \t (tab) and converts them into their special characters. Sometimes you want the actual backslash and letter instead of the processed result — that's where raw strings come in.
String.raw is a built-in tagged template literal function that returns the string exactly as you typed it, with all backslashes preserved.
Using String.raw
Call String.raw as a tag before a template literal:
let processed = `Line 1\nLine 2`;
console.log(processed);
// Output (two lines):
// Line 1
// Line 2
let raw = String.raw`Line 1\nLine 2`;
console.log(raw);
// Output (one line): Line 1\nLine 2
Notice how \n stays as the two characters \ and n instead of becoming a newline.
Common Use Cases
This is especially useful for:
- File paths on Windows:
String.rawC:\Users\Documents`` - Regular expression patterns:
String.raw\d+.\d+`` - Any text containing backslashes you want to keep literal
With Interpolation
String.raw still processes ${} expressions normally — only escape sequences are left raw:
let folder = "Documents";
let path = String.raw`C:\Users\${folder}\file.txt`;
console.log(path);
// Output: C:\Users\Documents\file.txt
Key Takeaway: String.raw preserves backslashes and escape sequences in their literal form, letting you access the raw characters you typed without JavaScript's usual escape processing.