Regex Replace All – Use the JavaScript g Flag

Local only

Fix a JavaScript regex replacement that changes only the first occurrence by enabling the global flag when every match should be replaced.

16 chars · 1 line

8 chars · 1 line

Pattern did not match the inputFlags: g

Regex replacement behavior

How to replace every regex match with the g flag

JavaScript regex replacement without g changes only the first match. In the sample, the first whitespace run becomes a hyphen while the second remains. Adding g makes the same replacement operate on every match. This tool is free to use. No account or payment is required.

Last updated

What you can do here

  • First-versus-global replacement
  • JavaScript g flag
  • Non-destructive output preview
  • Configurable regex flags
  • Local text transformation
  • Browser-local processing

Steps

  1. Run Replace without g and confirm that only the first matching occurrence changes.
  2. Add g once to the Flags field when all occurrences should be replaced.
  3. Retest the complete text and combine g with other flags only when their matching behavior is also required.

Global replacement is controlled by the regex flag

String.replace observes the RegExp's global flag. Without g it stops after the first regex match; with g it continues through the input using the same pattern and replacement string.

Replace-first versus replace-all example

Use the same whitespace pattern and replacement, then add g.

Without g

one-two  three

With g

one-two-three

Common questions

Frequently asked questions

Why does JavaScript regex replacement stop after one match?

A RegExp without the g flag replaces only its first match.

Should I use replaceAll instead?

This tool intentionally demonstrates native regex String.replace semantics; adding g is the normal regex way to replace all matches with that API.

Can g be combined with i or m?

Yes. Each supported flag controls a separate aspect of matching, and each flag may appear only once.

Debugging a specific Regex issue? Browse Regex troubleshooting.