JavaScript Reference ยท String
String.raw()
Reference for JavaScript String.raw(): the built-in tag function that returns template literals without processing escape sequences, useful for paths and regexes.
String.raw() is a tag function for template literals. Used as a tag, it returns the text exactly as you typed it in source code: backslashes are kept, and escape sequences such as \n or \t are not turned into newlines or tabs. Substitutions (${...}) are still evaluated and inserted.
That makes it handy for Windows paths, regular-expression sources and LaTeX-like text, where backslashes are frequent and doubling each one would be noisy.
String.raw`C:\Users\new`; // "C:\\Users\\new"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
String.raw`templateString` String.raw`string1${substitution1}string2` String.raw(callSite, ...substitutions)
| Name | Description |
|---|---|
callSite |
A template object. It must have a raw property that is an array-like of strings (the raw text pieces). With a tagged template, the engine provides it. |
substitutions |
Values inserted between the raw pieces. |
Return value: a string made by joining the raw pieces with the substitutions converted to strings. Extra substitutions are ignored and missing ones become empty.
Exceptions: TypeError if callSite.raw is missing or not array-like (including undefined or null).
Usage notes
- Raw means unprocessed in the source. A raw
\nhas length 2 (a backslash and ann), while the cooked string"\n"has length 1. - A template cannot end in a single backslash. The backslash would escape the closing backtick, so a raw path ending in
\is a syntax error. Append the final backslash through a substitution, such as${"\\"}, or concatenate it afterwards. - Escapes in substitutions are cooked. Only the literal text between substitutions is raw. A substitution like
${"\n"}already contains a real newline. - Invalid escapes are allowed in tagged templates. A normal template with
\ufollowed by non-hex text is a syntax error, but with a tag such asString.rawit is accepted. Tags can read the cooked value asundefinedand the raw text as is. - Not a path library.
String.rawjust keeps backslashes; it does not normalize or escape paths for you. In normal code, building paths with the platform's path tools is safer. - Regex literals need no tag.
/\d+/already keeps its backslashes;String.rawhelps only when you build aRegExpfrom a string. - The template object. In your own tag functions,
strings.rawis the same raw array thatString.rawuses.
Browser support
String.raw() arrived with ES2015 template literals and works in all current browsers and Node.js.