JavaScript RegExp toString() Method

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is toString()?

RegExp.prototype.toString() returns a readable string of the regex in /pattern/flags form. It does not search text — it only describes the RegExp for logs, errors, and debugging.

Remember
regex.toString()  → "/pattern/flags"

/hello/gi.toString()     → "/hello/gi"
new RegExp("a+b", "i")   → "/a+b/i"

source  → pattern only ("hello")
flags   → flags only ("gi")
toString → both with slashes ("/hello/gi")

Does not match text. Does not change lastIndex.
UsePrefer
Log / display the regexregex.toString()
Pattern text onlyregex.source
Clone a regexnew RegExp(regex.source, regex.flags)

How to Use toString()

Call it on any RegExp when you need a string description.

  1. Start with a regex literal or new RegExp(…).
  2. Call regex.toString() (or coerce with String(regex)).
  3. Use the result in logs, error messages, or UI debug panels.
  4. For rebuilding a regex, use source + flags instead of parsing the string.
PieceRequired?Role
RegExp objectYesValue to describe
ArgumentsNonetoString() takes no parameters
Return value—Always a string like /pat/flags

Pseudocode

Pseudocode
regex = /pattern/flags

result = "/" + regex.source + "/" + regex.flags
return result

// String(regex) and `${regex}` also call toString()
// No matching. No lastIndex updates.

Cheat Sheet

Keep these facts handy while logging or debugging regexes.

TopicDetail
Syntaxregex.toString()
Shape/pattern/flags
vs sourcePattern only, no slashes
vs flagsFlag letters only (gi, …)
CoercionString(regex), `${regex}`
Matches text?No — description only
StandardES3+ (universal)

Live Preview

Pick a regex and see toString(), source, and flags side by side.

Browser demo of RegExp.prototype.toString — same idea as the examples below.

Result
regex     = /hello/gi
toString() → "/hello/gi"
source     → "hello"
flags      → "gi"
typeof     → "string"

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

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

  1. Start with a literal. /hello/gi has pattern hello and flags gi.
  2. Call toString. The method builds a slash-wrapped display string.
  3. Flags trail the close slash. Result looks like source code: /hello/gi.
  4. Type is string. You get text for logging — not another RegExp object.

Example 2 — toString() vs source vs flags

Break a regex into its display string and component properties.

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

  1. Constructor or literal. Both produce the same toString() shape.
  2. Full display. toString() joins pattern and flags with slashes.
  3. Parts separately. source is the pattern; flags is the flag string.
  4. Clone tip. Prefer new RegExp(regex.source, regex.flags) over parsing the display string.

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

  1. Validate first. test() checks the value against the rule.
  2. On failure, describe the rule. toString() shows exactly which pattern was expected.
  3. Templates coerce too. ${zipRule} would call toString() automatically.
  4. Why it helps. Logs and errors become self-explanatory without opening DevTools.

Edge Cases & Pitfalls

Check these before relying on toString() in real projects.

clone

Do not parse toString() to rebuild a regex

Use new RegExp(regex.source, regex.flags). Parsing the slash form breaks on patterns that contain /.

escape

Escapes may look different from your source code

source (and therefore toString()) shows the engine’s stored pattern, which can differ slightly from how you typed the literal.

role

It never matches text

toString() is for description only. Use test() or exec() to search a string.

empty

Empty pattern still has slashes

/(?:)/.toString() or an empty constructor pattern still returns a slash-wrapped string such as /(?:)/.

Browser & Runtime Support

RegExp.prototype.toString() is part of core JavaScript (ES3+). It works everywhere without polyfills.

✓ Baseline · ES3+

RegExp.prototype.toString()

Supported in every modern and legacy browser, plus all Node.js versions. Universal way to stringify a RegExp.

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
toString() Excellent

Bottom line: Safe everywhere. Use toString() for logs and errors; use source and flags when you need the parts separately.

Performance Notes

ApproachCostBest for
regex.toString()Tiny string buildLogs, errors, debug UI
regex.source / .flagsProperty readsCloning or inspecting parts
Parse toString() outputFragileAvoid — use source + flags

toString() is cheap and fine for logging. Do not call it in hot match loops — matching itself is the expensive part, and stringifying every time only adds noise.

Key Takeaways

  • Role: toString() returns /pattern/flags as a string.
  • Parts: use source and flags when you need them separately.
  • Coercion: String(regex) and templates call toString() too.
  • Clone: new RegExp(source, flags) — do not parse the slash string.

One line: toString() turns a RegExp into a clear /pattern/flags label for humans — not a tool for matching.

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 appended after the closing slash.
Yes. String(regex) and regex.toString() both use the same conversion. Template literals like `${regex}` also call 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 and logs. Prefer source and flags when building a new RegExp programmatically: new RegExp(regex.source, regex.flags).
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.

Next: constructor property

Learn what regex.constructor points to and when you might use it.

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.

8 people found this page helpful