RegExp.prototype.source
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
source
は RegExp
のアクセサープロパティで、正規表現オブジェクトのソーステキストの入った文字列を返します。これには、両端の 2 つのスラッシュやフラグは含まれません。
試してみましょう
const regex1 = /fooBar/gi;
console.log(regex1.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
プロパティは正規表現リテラルの 2 つのスラッシュの間のテキストです。この言語では、返される文字列が適切にエスケープされている必要があり、source
の両端にスラッシュを連結すると、解析可能な正規表現リテラルが形成されます。例えば、new RegExp("/")
の場合、source
は \\/
です。これは /
を生成し、結果のリテラルは ///
です。同様に、改行文字はすべてエスケープされます。結果が解析可能である限り、他にも文字は必要ありません。空文字列の正規表現では (?:)
という文字列を返します。
例
source の使用
js
const regex = /fooBar/gi;
console.log(regex.source); // "fooBar", /.../ と "gi" は含まれません。
空の正規表現とエスケープ
js
new RegExp().source; // "(?:)"
new RegExp("\n").source === "\\n"; // true。ES5 以降
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-get-regexp.prototype.source |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
source | ||||||||||||||
"(?:)" for empty regexps | ||||||||||||||
Line breaks and slashes are escaped | ||||||||||||||
Prototype accessor property (ES2015) |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.