The String.raw() method in TypeScript is used to obtain the raw string representation of template literals without interpreting escape characters. This is particularly useful for preserving escape sequences and special characters.
Syntax
String.raw(string: TemplateStringsArray, ...values: any[]): string
String.raw`templateString`;Parameters
- string (TemplateStringsArray): Here you have to pass the template literal array object.
- values (any[]): Here you have to pass the value containing the substituted values.
- templateString: Here you have to pass the template literal string.
Return Value
It will return the raw string form of the template literal.
Example 1: Preserving Escape Sequences
In this example, the String.raw() method is used to preserve escape sequences in the template literal.
let filePath: string = String.raw`C:\Users\username\Documents\myfile.txt`;
console.log(filePath);
Output:
C:\Users\username\Documents\myfile.txtExample 2: Using String.raw() with Unicode Characters
In this example, the String.raw() method is used to demonstrate the difference between regular and raw string representations of Unicode characters.
let regularUnicode: string = `\u2607`;
let rawUnicode: string = String.raw`\u2607`;
console.log("Unicode Regular:");
console.log(regularUnicode);
console.log("Unicode Raw:");
console.log(rawUnicode);
Output:
Unicode Regular:
☇
Unicode Raw:
\u2607