JavaScript RegExp toString() Method (original) (raw)

Last Updated : 05 Dec, 2024

The **RegExp.toString() method in JavaScript is used to return the string representation of a regular expression object. It converts the regular expression to a string, including its pattern and flags.

JavaScript `

let reg1 = /hello/i; let reg2 = /\d{3}-\d{2}-\d{4}/;

console.log(reg1.toString()); console.log(reg2.toString());

`

Output

/hello/i /\d{3}-\d{2}-\d{4}/

**Syntax

let regexString = regex.toString();

**Now Let's see some of the uses of RegExp toString() Method

1. Debugging Regular Expressions

The toString() method is particularly useful for debugging when you need to log or inspect the regular expression in its literal string format. Here’s an example:

JavaScript `

let regex = /^[A-Za-z0-9]+$/;

console.log("Regex pattern:", regex.toString());

`

Output

Regex pattern: /^[A-Za-z0-9]+$/

This output makes it easier to verify that the regex pattern is what you expected.

2. Dynamic Regex Generation

If you're generating regular expressions dynamically based on user input or other conditions, toString() can be helpful to view or log the constructed regex:

JavaScript `

let pattern = "\d{3}-\d{2}-\d{4}"; let regex = new RegExp(pattern, "g");

console.log(regex.toString());

`

Output

/\d{3}-\d{2}-\d{4}/g

This shows how the dynamically created regular expression looks when converted to a string.

Key Points About toString()