Replacing in JavaScript

From the JavaScript Regular Expressions cheat sheet · String Methods · verified Jul 2026

Replacing

Using regex with replace methods

javascript
// replace() - First match only
"hello world".replace(/o/, "0")   // "hell0 world"

// replaceAll() - All matches
"hello world".replace(/o/g, "0")  // "hell0 w0rld"
"hello world".replaceAll(/o/g, "0") // "hell0 w0rld"

// Replacement patterns
"John Smith".replace(/(\w+) (\w+)/, "$2, $1")
// "Smith, John"

// Named groups in replacement
"2024-03-15".replace(
  /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/,
  "$<month>/$<day>/$<year>"
)  // "03/15/2024"

// Function replacer
"hello123world456".replace(/\d+/g, (match) => {
  return match * 2  // Double numbers
})  // "hello246world912"

// Advanced replacer function
"John Smith, Jane Doe".replace(
  /(\w+) (\w+)/g,
  (full, first, last, offset, string) => {
    return \`\${last.toUpperCase()}, \${first[0]}.\`
  }
)  // "SMITH, J., DOE, J."

// Special replacement patterns
$&   Matched substring
$\`  Text before match
$'   Text after match
$$   Literal $
$n   Capture group n
💡 Use function replacer for complex transformations
⚡ $& inserts the entire match in replacement
📌 replaceAll() requires global flag or throws error
🟢 Named groups with $<name> improve readability
replacesubstitution

More JavaScript tasks

Back to the full JavaScript Regular Expressions cheat sheet