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
Parameter | Optional/Required | Description |
---|---|---|
strings | required | An array of template strings to process. |
sub1, sub2, ... , subN | optional | Substitutions 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,
- We declare variables
name
andage
. - We use
String.raw
with a template string containing placeholders forname
andage
. - The placeholders are substituted with the actual values, and the raw string is stored in
info
. - 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,
- We create an array
chars
with characters 'a', 'b', and 'c'. - We use
String.raw
with a template string containing placeholders for the array elements. - The placeholders are substituted with the array values, and the raw string is stored in
rawString
. - 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,
- We create an array
stringsList
with strings 'Hello' and 'World'. - We use
String.raw
with a template string containing placeholders for the array elements. - The placeholders are substituted with the array values, and the raw string is stored in
rawTemplate
. - 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.