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());
/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 ExpressionsThe 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());
Regex pattern: /^[A-Za-z0-9]+$/
This output makes it easier to verify that the regex pattern is what you expected.
2. Dynamic Regex GenerationIf 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());
/\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()RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4