regex global replace — replace all matches in JavaScript, Python, sed
Quick Answer
// JavaScript — /g flag
'foo foo foo'.replace(/foo/g, 'bar')
// 'bar bar bar'
# Python — re.sub replaces all by default
import re
re.sub(r'foo', 'bar', 'foo foo foo')
# 'bar bar bar'
# sed — s/old/new/g
echo "foo foo foo" | sed 's/foo/bar/g'
Usage
Without the global flag, most regex replace functions only replace the first match.
Other causes & fixes
JavaScript — String.replaceAll() (ES2021)
// replaceAll with a string pattern (no regex needed)
'foo foo foo'.replaceAll('foo', 'bar')
// 'bar bar bar'
// replaceAll requires /g when using regex
'foo foo foo'.replaceAll(/foo/g, 'bar')
Python — limit number of replacements
import re
# Only replace first 2 occurrences
re.sub(r'foo', 'bar', 'foo foo foo', count=2)
# 'bar bar foo'
Case-insensitive global replace
// JavaScript
'Foo FOO foo'.replace(/foo/gi, 'bar')
// 'bar bar bar'
# Python
re.sub(r'foo', 'bar', 'Foo FOO foo', flags=re.IGNORECASE)
# 'bar bar bar'
# sed (case-insensitive + global)
echo "Foo FOO foo" | sed 's/foo/bar/gI'
Dynamic replacement with a function (JavaScript)
'hello world'.replace(/(\w+)/g, (match) => match.toUpperCase())
// 'HELLO WORLD'
Related