Open In App

JavaScript String raw() Method

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The raw() method in JavaScript is a template string tag function that returns the raw string form of template literals.

It can be used to get the raw string form of a template literal without processing escape sequences. This method is useful when dealing with special characters that should not be escaped.

Syntax:

String.raw(callSite, ...substitutions) 

Parameters:

This method takes two parameters:

Parameter

Description

callSite

An object representing the template string literal.

substitutions

Optional, values to replace placeholders in the template string.

Return Value:

Raw string form of the template literal.

JavaScript String raw() Method Examples

Example 1: Using String.raw() with template literals

Using String.raw() with template literals provides a way to access the raw string form of the template without interpreting escape sequences. Here, String.raw allows the backslashes in the template literal to be preserved as is, producing the raw string "C:\Users\John\Desktop\file.txt". Without String.raw, the backslashes would have been interpreted as escape sequences, leading to unexpected results.

JavaScript
const path = String.raw`C:\Users\John\Desktop\file.txt`;
console.log(path);

Output
C:\Users\John\Desktop\file.txt

Example 2: Escaping in String.raw()

In JavaScript, String.raw() is used to produce a raw string from template literals. This means that escape sequences such as \n or \t are not interpreted as newline or tab characters. Here, String.raw() produces a raw string where the \n sequence is not interpreted as a newline character but instead remains as literal characters \ and n.

JavaScript
const str = String.raw`First line\nSecond line`;
console.log(str);

Output
First line\nSecond line

Supported Browsers: 

We have a complete list of Javascript string methods, to check those please go through this Javascript String reference article.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads