試一試
const regex = /fooBar/gi;
console.log(regex.source);
// Expected output: "fooBar"
console.log(new RegExp().source);
// Expected output: "(?:)"
console.log(new RegExp("\n").source === "\\n");
// Expected output: true (starting with ES5)
// Due to escaping
描述
從概念上講,source 屬性是正則表示式字面量中兩個斜槓之間的文字。語言要求返回的字串必須被正確轉義,以便當 source 與兩側的斜槓連線時,它將形成一個可解析的正則表示式字面量。例如,對於 new RegExp("/"),source 是 \\/,因為如果它生成 /,則生成的字面量將是 ///,這是一個行註釋。同樣,所有 行終止符都將被轉義,因為行終止符字元會中斷正則表示式字面量。對於其他字元沒有要求,只要結果是可解析的即可。對於空正則表示式,將返回字串 (?:)。
示例
使用 source
js
const regex = /fooBar/gi;
console.log(regex.source); // "fooBar", doesn't contain /.../ and "gi".
空正則表示式和轉義
js
new RegExp().source; // "(?:)"
new RegExp("\n").source === "\\n"; // true, starting with ES5
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-get-regexp.prototype.source |
瀏覽器相容性
載入中…