JavaScript Tutorials

JavaScript String.raw()
Syntax & Examples

String.raw() static-method

The `raw` method of String class in JavaScript returns a string created from a raw template string.


Syntax of String.raw()

The syntax of String.raw() static-method is:

String.raw(strings)
String.raw(strings, sub1)
String.raw(strings, sub1, sub2)
String.raw(strings, sub1, sub2, /* …, */ subN)

String.raw`templateString`

This raw() static-method of String returns a string created from a raw template string.

Parameters

ParameterOptional/RequiredDescription
stringsrequiredAn array of template strings to process.
sub1, sub2, ... , subNoptionalSubstitutions to replace placeholders in the template strings.

Return Type

String.raw() returns value of type String.



✐ Examples

1 Using raw template with variables

In this example,

  1. We declare variables name and age.
  2. We use String.raw with a template string containing placeholders for name and age.
  3. The placeholders are substituted with the actual values, and the raw string is stored in info.
  4. We log info to the console.

JavaScript Program

const name = 'John';
const age = 30;
const info = String.raw`Name: ${name}, Age: ${age}`;
console.log(info);

Output

Name: John, Age: 30

2 Using raw template with an array of characters

In this example,

  1. We create an array chars with characters 'a', 'b', and 'c'.
  2. We use String.raw with a template string containing placeholders for the array elements.
  3. The placeholders are substituted with the array values, and the raw string is stored in rawString.
  4. We log rawString to the console.

JavaScript Program

const chars = ['a', 'b', 'c'];
const rawString = String.raw`Chars: ${chars[0]}, ${chars[1]}, ${chars[2]}`;
console.log(rawString);

Output

Chars: a, b, c

3 Using raw template with an array of strings

In this example,

  1. We create an array stringsList with strings 'Hello' and 'World'.
  2. We use String.raw with a template string containing placeholders for the array elements.
  3. The placeholders are substituted with the array values, and the raw string is stored in rawTemplate.
  4. We log rawTemplate to the console.

JavaScript Program

const stringsList = ['Hello', 'World'];
const rawTemplate = String.raw`Strings: ${stringsList[0]}, ${stringsList[1]}`;
console.log(rawTemplate);

Output

Strings: Hello, World

Summary

In this JavaScript tutorial, we learned about raw() static-method of String: the syntax and few working examples with output and detailed explanation for each example.