String.raw()
String.raw() 靜態方法是 模板字面量 的一個標籤函式。這類似於 Python 中的 r 字首,或 C# 中的 @ 字首用於字串字面量。它用於獲取模板字面量的原始字串形式 — 也就是說,替換(例如 ${foo})會被處理,但轉義序列(例如 \n)則不會。
試一試
// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Development\profile\about.html`;
console.log(`The file was uploaded from: ${filePath}`);
// Expected output: "The file was uploaded from: C:\Development\profile\about.html"
語法
String.raw(strings)
String.raw(strings, sub1)
String.raw(strings, sub1, sub2)
String.raw(strings, sub1, sub2, /* …, */ subN)
String.raw`templateString`
引數
字串-
格式正確的模板字面量陣列物件,例如
{ raw: ['foo', 'bar', 'baz'] }。應該是一個具有raw屬性的物件,其值是一個類陣列物件,包含字串。 sub1, …,subN-
包含替換值。
templateString-
一個 模板字面量,可選地帶有替換(
${...})。
返回值
給定模板字面量的原始字串形式。
異常
TypeError-
如果第一個引數沒有
raw屬性,或者raw屬性是undefined或null,則丟擲此錯誤。
描述
在大多數情況下,String.raw() 與模板字面量一起使用。上面提到的第一個語法很少使用,因為 JavaScript 引擎會自動為您呼叫它,並提供正確的引數(就像其他 標籤函式 一樣)。
String.raw() 是唯一的內建模板字面量標籤。它的語義與非標籤字面量非常接近,因為它會連線所有引數並返回一個字串。您甚至可以使用普通 JavaScript 程式碼重新實現它。
警告: 您不應直接將 String.raw 用作“身份”標籤。有關如何實現此功能的說明,請參閱 構建身份標籤。
如果 String.raw() 使用的物件,其 raw 屬性沒有 length 屬性或 length 為非正數,則返回空字串 ""。如果 substitutions.length < strings.raw.length - 1(即,替換項不足以填充佔位符 — 這在格式正確的標籤模板字面量中不會發生),則剩餘的佔位符將用空字串填充。
示例
使用 String.raw()
String.raw`Hi\n${2 + 3}!`;
// 'Hi\\n5!', the character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.
String.raw`Hi\u000A!`;
// 'Hi\\u000A!', same here, this time we will get the
// \, u, 0, 0, 0, A, 6 characters.
// All kinds of escape characters will be ineffective
// and backslashes will be present in the output string.
// You can confirm this by checking the .length property
// of the string.
const name = "Bob";
String.raw`Hi\n${name}!`;
// 'Hi\\nBob!', substitutions are processed.
String.raw`Hi \${name}!`;
// 'Hi \\${name}!', the dollar sign is escaped; there's no interpolation.
在 RegExp 中使用 String.raw
將 String.raw 模板字面量與 RegExp() 建構函式結合使用,可以建立帶有動態部分的正則表示式(這在使用正則表示式字面量時是不可能的),而無需對正則表示式轉義序列進行雙重轉義(\\)(在使用普通字串字面量時也是不可能的)。這對於包含大量斜槓的字串(如檔案路徑或 URL)也很有用。
// A String.raw template allows a fairly readable regular expression matching a URL:
const reRawTemplate = new RegExp(
String.raw`https://developer\.mozilla\.org/en-US/docs/Web/JavaScript/Reference/`,
);
// The same thing with a regexp literal looks like this, with \/ for
// each forward slash:
const reRegexpLiteral =
/https:\/\/developer\.mozilla\.org\/en-US\/docs\/Web\/JavaScript\/Reference\//;
// And the same thing written with the RegExp constructor and a
// traditional string literal, with \\. for each period:
const reStringLiteral = new RegExp(
"https://developer\\.mozilla\\.org/en-US/docs/Web/JavaScript/Reference/",
);
// String.raw also allows dynamic parts to be included
function makeURLRegExp(path) {
return new RegExp(String.raw`https://developer\.mozilla\.org/${path}`);
}
const reDynamic = makeURLRegExp("en-US/docs/Web/JavaScript/Reference/");
const reWildcard = makeURLRegExp(".*");
構建身份標籤
許多工具會特殊處理由特定名稱標記的字面量。
// Some formatters will format this literal's content as HTML
const doc = html`<!doctype html>
<html lang="en-US">
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>`;
人們可能會天真地實現 html 標籤,如下所示:
const html = String.raw;
實際上,這對於上述情況是有效的。但是,由於 String.raw 會連線原始字串字面量而不是“已解析”的字面量,因此轉義序列將不會被處理。
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\\n</canvas>"
對於一個“真正的身份”標籤(即標籤僅用於標記,不更改字面量的值),這可能不是您想要的。在這種情況下,您可以建立一個自定義標籤,並將“已解析”(即已處理轉義序列)的字面量陣列傳遞給 String.raw,假裝它們是原始字串。
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);
// Some formatters will format this literal's content as HTML
const doc = html`<canvas>\n</canvas>`;
// "<canvas>\n</canvas>"; the "\n" becomes a line break
請注意,第一個引數是一個帶有 raw 屬性的物件,該屬性的值是一個類陣列物件(具有 length 屬性和整數索引),代表模板字面量中分隔的字串。其餘引數是替換項。由於 raw 值可以是任何類陣列物件,因此它甚至可以是字串!例如,'test' 被視為 ['t', 'e', 's', 't']。以下與 `t${0}e${1}s${2}t` 等效:
String.raw({ raw: "test" }, 0, 1, 2); // 't0e1s2t'
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.raw |
瀏覽器相容性
載入中…