JavaScript RegExp toString() Method

Definition and Usage

toString() The method returns the string value of the regular expression.

Instance

Example 1

Returns the string value of the regular expression:

let pattern = /Hello World/g;
let text = pattern.toString();

Try It Yourself

Example 2

Returns the string value of the regular expression:

let pattern = new RegExp("Hello World", "g");
let text = pattern.toString();

Try It Yourself

Syntax

RegexpObject.toString()

Parameter

None.

Return Value

Type Description
String String representation of RegExp.

Technical Details

Thrown

Type Description
TypeError This exception is thrown when the object called by this method is not RegExp.

Description

The RegExp.toString() method returns the string representation of the regular expression in the form of a regular expression literal.

Note

Escape sequences are not allowed to be added by the implementation, so that the returned string can be a legal regular expression literal.

Please think about the regular expression created by the expression new RegExp("/","g"). One implementation of RegExp.toString() returns "///g" for this regular expression, and it may also add escape sequences, returning "/\//g".

Browser Support

toString() Is ECMAScript1 (ES1) Feature.

All Browsers Fully Support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support