toString() method returns a string representing the regular expression.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

regexObj.toString();
					

返回值

A string representing the given object.

描述

RegExp object overrides the toString() 方法在 Object object; it does not inherit Object.prototype.toString() . For RegExp objects, the toString() method returns a string representation of the regular expression.

范例

使用 toString()

The following example displays the string value of a 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'
					

Empty regular expressions and escaping

Starting with ECMAScript 5, an empty regular expression returns the string "/(?:)/" and line terminators such as "\n" are escaped:

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

规范

规范
ECMAScript (ECMA-262)
The definition of 'RegExp.prototype.toString' in that specification.

浏览器兼容性

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. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
toString Chrome 1 Edge 12 Firefox 1 IE 4 Opera 5 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0 nodejs Yes
Escaping Chrome 73 Edge 12 Firefox 38 IE 9 Opera 60 Safari 6 WebView Android 73 Chrome Android 73 Firefox Android 38 Opera Android 52 Safari iOS 6 Samsung Internet Android No nodejs Yes

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: