toString() turns a RegExp object into a readable /pattern/flags string. Use it for debugging, logging, error messages, and displaying the active pattern in tools or UI—without running a match.
01
Syntax
regex.toString()
02
/pat/flags
Literal style
03
source
Pattern only
04
flags
gi msu…
05
String()
Same result
06
Debug
Log & trace
Fundamentals
Introduction
A RegExp object stores a pattern and flags internally. When you console.log a regex or embed it in a template literal, JavaScript needs a human-readable form. That is what toString() provides: a string that looks like the regex literal you might write in source code.
Unlike test() or exec(), toString() does not search text. It only describes the regex itself. That makes it perfect for debugging (“which pattern failed?”), building error messages, and showing users what rule is being applied.
Concept
Understanding the toString() Method
regex.toString() returns a string built from the RegExp’s source and flags:
Format — "/" + source + "/" + flags, e.g. "/\\d+/g".
No matching — purely descriptive; does not touch lastIndex or input strings.
Coercion — String(regex), "" + regex, and `${regex}` all use the same conversion.
Empty flags — when no flags are set, the result ends with / and no trailing letters: "/hello/".
💡
Beginner Tip
For programmatic reuse, read regex.source and regex.flags separately instead of parsing toString() output. The source property gives the pattern; flags gives letters like "gi".
Usage
How to Use toString()
Call toString() when you need a display string, or rely on implicit conversion in logs and templates:
JavaScript
const regex = /^\w+@\w+\.\w+$/i;
console.log(regex.toString()); // /^\w+@\w+\.\w+$/i
console.log(`Pattern: ${regex}`); // same via coercion
throw new Error(`Invalid input for ${regex.toString()}`);
Pair with test() or exec() in error handlers so users see both whether validation failed and which pattern was used.
Foundation
📝 Syntax
JavaScript
regex.toString()
Parameters
None.
Return value
A string in /pattern/flags form.
Related properties
JavaScript
regex.source // pattern text only
regex.flags // flag letters only
regex.toString() // "/" + source + "/" + flags
Cheat Sheet
⚡ Quick Reference
Goal
Code
Full literal-style string
regex.toString()
Pattern text only
regex.source
Flags only
regex.flags
Implicit conversion
String(regex)
Rebuild RegExp
new RegExp(regex.source, regex.flags)
Check a match
Use test() or exec() instead
Compare
📋 toString() vs source vs flags
Choose the property that matches what you need to read or display.
toString()
/\d+/g
Full literal-style string
source
\d+
Pattern body only
flags
g
Flag letters only
String()
same as toString
Coercion alias
Hands-On
Examples Gallery
Open DevTools Console (F12) or use Try-it links. Examples cover literal regexes, constructor-created patterns, logging, source/flags breakdown, and template literal coercion.
📚 Getting Started
Convert a RegExp to a readable string.
Example 1 — Basic toString() on a Literal
See the string form of a regex with multiple flags.
The output mirrors regex literal syntax: slashes around the pattern, flags appended after the closing slash. The result is always a string, not a RegExp object.
📈 Practical Patterns
Constructor regexes, logging, and property breakdown.
Example 2 — new RegExp() and toString()
Dynamic patterns produce the same string format as literals.
JavaScript calls toString() when a RegExp is coerced to string. Explicit regex.toString() is clearest in code; implicit conversion is fine in logs and template literals.
Applications
🚀 Common Use Cases
Console debugging — log the active pattern when regex behavior is unexpected.
Error messages — tell users or developers which validation rule failed.
Test output — display expected patterns in unit test failure diffs.
Documentation tools — show live regex config in admin or config panels.
Serialization hints — pair with source and flags for storage.
Learning aids — compare literal syntax with dynamic RegExp objects.
Watch Out
Important Considerations
Not for matching — toString() does not test or exec against strings.
Do not parse output — prefer source and flags over splitting the string.
Escaping in source — source may show double backslashes for escaped characters.
Not JSON-safe alone — store source and flags as separate fields when persisting.
Differs from match results — match arrays have their own toString() behavior (comma-joined).
Empty flags omitted visually — /hello/ has no flag letters after the slash.
🧠 How toString() Builds the String
1
Read source
Get the pattern text from the RegExp internal slot (exposed as source).
Pattern
2
Read flags
Collect active flag letters (g, i, m, s, u, y, d) into a string.
Flags
3
Wrap with slashes
Concatenate "/", source, "/", and flags into one string.
Format
4
📄
Return string
The result is ready for logs, templates, or error messages—no matching involved.
Important
📝 Notes
toString() is inherited from Object.prototype but overridden on RegExp.
RegExp.prototype.toString() has been part of JavaScript since ES3.
✓ Baseline · ES3+
RegExp toString()
Supported in every browser and Node.js version. source and flags properties are ES2015+.
99%Universal API
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · Modern WebView
Full support
RegExp toString()Excellent
Bottom line: Safe everywhere. Use toString() for readable regex output in logs and errors.
Wrap Up
Conclusion
toString() converts a RegExp object into a familiar /pattern/flags string. It is ideal for debugging, logging, and error messages. For programmatic access to the parts, use source and flags directly instead of parsing the string.
Next, learn the constructor property for type checks and RegExp identity, or review test() for boolean validation.
Read source and flags when cloning or storing regexes
Prefer explicit regex.toString() in non-obvious contexts
Document dynamic patterns by logging toString() output
Combine with test() messages for clearer validation errors
❌ Don’t
Parse toString() output with regex or string splits
Assume the string can always be pasted back as a valid literal
Use toString() when you meant to match text
Confuse RegExp toString() with match result arrays
Serialize regexes as a single string without separate flag handling
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about toString()
Display regex patterns as readable strings.
5
Core concepts
📝01
Format
/pat/flags
Output
📈02
source
Pattern only.
Property
🔖03
flags
Letters only.
Property
🔍04
Debug
Log errors.
Use case
⚠05
No match
Display only.
Pitfall
❓ Frequently Asked Questions
toString() returns a string in the form /pattern/flags—for example, /hello/gi. It includes the opening and closing slashes and any flags (g, i, m, etc.) appended after the closing slash.
Yes. String(regex) and regex.toString() both call the same internal conversion. Template literals like `${regex}` also use toString() under the hood.
source returns only the pattern text without slashes or flags. toString() wraps source and flags together as a literal-style string: `/` + source + `/` + flags.
Mostly for debugging. The output looks like a literal, but copying it into source code may need escaping fixes for complex patterns. Prefer source and flags when building a new RegExp programmatically.
No. toString() only describes the RegExp object. It does not search strings or change lastIndex.
RegExp.prototype.toString() has been part of JavaScript since ES3. It works in every browser and Node.js version.
Did you know?
When you console.log a RegExp in modern DevTools, the browser often shows the same /pattern/flags format that toString() returns—making it easy to copy the pattern you are debugging.