Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
String.raw`C:\Users\new`; // "C:\\Users\\new"

Try it

JS Raw versus cooked

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Regex sources and a manual call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 \n has length 2 (a backslash and an n), 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 \u followed by non-hex text is a syntax error, but with a tag such as String.raw it is accepted. Tags can read the cooked value as undefined and the raw text as is.
  • Not a path library. String.raw just 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.raw helps only when you build a RegExp from a string.
  • The template object. In your own tag functions, strings.raw is the same raw array that String.raw uses.

Browser support

String.raw() arrived with ES2015 template literals and works in all current browsers and Node.js.