RegExp.prototype.toString()

toString() メソッドは正規表現を表す文字列を返します。

試してみましょう

構文

regexObj.toString();

返値

呼び出し元のオブジェクトを表す文字列です。

解説

RegExp オブジェクトの toString() メソッドは、 Object オブジェクトのものを上書きします。つまり Object.prototype.toString() を継承しません。 RegExp オブジェクトにおける toString() メソッドは、その正規表現オブジェクトを表す文字列を返します。

toString() の使用

以下の例は RegExp オブジェクトの文字列の値を表示します。:

var myExp = new RegExp('a+b+c');
console.log(myExp.toString());  // logs '/a+b+c/'

var foo = new RegExp('bar', 'g');
console.log(foo.toString());    // logs '/bar/g'

空の正規表現とエスケープ

ECMAScript 5 以降では、空の正規表現は "/(?:)/" 文字列を返し、"\n" などの行末記号はエスケープされます。

new RegExp().toString(); // "/(?:)/"

new RegExp('\n').toString() === '/\n/';  // true, prior to ES5
new RegExp('\n').toString() === '/\\n/'; // true, starting with ES5

仕様書

Specification
ECMAScript Language Specification
# sec-regexp.prototype.tostring

ブラウザーの互換性

BCD tables only load in the browser

関連情報