JavaScript string.raw() method


The String.raw() method in JavaScript is a template literal tag function that is used to access the raw string form of a template literal. This method is particularly useful when you want to create a string without any escape sequences being processed, allowing you to include backslashes and other characters literally.

Syntax:

String.raw(template, ...substitutions)
  • template: A template literal containing the raw string values. It is passed as the first argument to String.raw(), and it is an array of strings.
  • ...substitutions: Additional values that are interpolated into the string, just like with regular template literals.

Return Value:

  • Returns a string constructed from the raw template string and any substitutions.

Example 1: Basic Usage

Using String.raw() with a simple template literal.

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

In this example, the \n is treated as two characters (a backslash and an "n") instead of being interpreted as a newline character.

Example 2: Including Backslashes

The String.raw() method allows you to include backslashes in the string.

const path = String.raw`C:\Users\Name\Documents`; console.log(path); // "C:\Users\Name\Documents"

Here, the backslashes are preserved, making it useful for file paths.

Example 3: Using Substitutions

You can also include substitutions in the raw string.

const name = "Alice"; const rawStr = String.raw`Hello, ${name}!\nWelcome to the party.`; console.log(rawStr); // "Hello, Alice!\nWelcome to the party."

In this example, ${name} is substituted with "Alice", and \n remains as a literal backslash and "n".

Example 4: Accessing the Raw String Values

When using String.raw() with template literals, it allows you to inspect the raw string values as an array.

const raw = String.raw`Hello\nWorld!`; console.log(raw.length); // 12 (length includes the raw characters) console.log(raw[5]); // "\n"

In this case, raw.length gives the number of characters in the raw string, and accessing raw[5] retrieves the backslash.

Summary:

  • The String.raw() method provides a way to create strings without processing escape sequences.
  • It is useful for preserving backslashes and creating raw string representations.
  • You can use it with template literals and include substitutions, but escape sequences like \n will remain as literal characters.
  • This method is beneficial in scenarios where you need to work with string literals that include escape characters, such as file paths, regular expressions, or multiline strings.