JavaScript RegExp toString() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
String output

What You’ll Learn

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

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.

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.
  • CoercionString(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".

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.

📝 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

⚡ Quick Reference

GoalCode
Full literal-style stringregex.toString()
Pattern text onlyregex.source
Flags onlyregex.flags
Implicit conversionString(regex)
Rebuild RegExpnew RegExp(regex.source, regex.flags)
Check a matchUse test() or exec() instead

📋 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

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.

JavaScript
const regex = /hello/gi;



console.log(regex.toString());  // "/hello/gi"

console.log(typeof regex.toString());  // "string"
Try It Yourself

How It Works

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
const regex = new RegExp("a+b", "i");



console.log(regex.toString());  // "/a+b/i"

console.log(regex.source);      // "a+b"

console.log(regex.flags);       // "i"
Try It Yourself

How It Works

Whether you use a literal or new RegExp(), toString() formats the result the same way. Use source and flags when you need the parts separately.

Example 3 — Debug Validation Failures

Include the pattern in an error when test() fails.

JavaScript
const zipRule = /^\d{5}$/;



function validateZip(value) {

  if (!zipRule.test(value)) {

    return `Invalid ZIP. Expected pattern ${zipRule.toString()}`;

  }

  return "Valid";

}



console.log(validateZip("90210"));  // Valid

console.log(validateZip("9021"));   // Invalid ZIP. Expected pattern /^\d{5}$/
Try It Yourself

How It Works

Showing toString() in errors helps developers see exactly which rule failed without manually inspecting the RegExp object in DevTools.

Example 4 — Compare toString(), source, and flags

Break a regex into its display string and component properties.

JavaScript
const regex = /\d+/g;



console.log("toString:", regex.toString());  // /\d+/g

console.log("source:", regex.source);        // \d+

console.log("flags:", regex.flags);          // g
Try It Yourself

How It Works

toString() combines source and flags with slashes. To clone a regex, use new RegExp(regex.source, regex.flags) rather than parsing the string.

Example 5 — Implicit Conversion with String() and Templates

These approaches call toString() automatically.

JavaScript
const regex = /world/;



console.log(String(regex));       // "/world/"

console.log("" + regex);          // "/world/"

console.log(`Found with ${regex}`);  // Found with /world/
Try It Yourself

How It Works

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.

🚀 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.

Important Considerations

  • Not for matchingtoString() does not test or exec against strings.
  • Do not parse output — prefer source and flags over splitting the string.
  • Escaping in sourcesource 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.

📝 Notes

  • toString() is inherited from Object.prototype but overridden on RegExp.
  • Previous topic: compile() legacy method.
  • Next topic: constructor property.
  • See test() for boolean matching.
  • See global property for the g flag.
  • Clone safely: new RegExp(r.source, r.flags).

Browser & Runtime Support

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 Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
RegExp toString() Excellent

Bottom line: Safe everywhere. Use toString() for readable regex output in logs and errors.

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.

💡 Best Practices

✅ Do

  • Use toString() in logs and error messages
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about toString()

Display regex patterns as readable strings.

5
Core concepts
📈 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.

Continue to RegExp constructor

Learn how the constructor property identifies RegExp objects.

constructor tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful