replace()
replace(
str,pattern,replacement):string
Replaces matches for pattern in string with replacement.
DEPRECATED
Use string.replace() directly instead.
Parametersโ
str: string | null | undefinedโ
The string to modify.
pattern: string | RegExpโ
The pattern to replace.
replacement: stringโ
The replacement string.
Returns: stringโ
The modified string.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
replace (Lodash, es-toolkit, Ramda) ยท โ (Remeda, Radashi, Effect, Modern Dash, Antfu)
Exampleโ
// โ Deprecated approach
replace('hello world', 'world', 'there'); // => 'hello there'
replace('foo bar foo', /foo/g, 'baz'); // => 'baz bar baz'
// โ
Recommended approach
'hello world'.replace('world', 'there'); // => 'hello there'
'foo bar foo'.replace(/foo/g, 'baz'); // => 'baz bar baz'
How it works?โ
Replaces matches in string.
Deprecated: Use string.replace() directly.
Native Equivalentโ
// โ replace(str, pattern, replacement)
// โ
str.replace(pattern, replacement)
Use Casesโ
Replace substring ๐โ
Replace part of a string.
"hello world".replace("world", "there");
// => "hello there"
Replace all occurrencesโ
Replace every match.
"a-b-c".replaceAll("-", "_");
// => "a_b_c"
Pattern replacementโ
Use regex for complex replacements.
"hello123world".replace(/\d+/g, "-");
// => "hello-world"
Mask sensitive data for displayโ
Partially hide sensitive information before displaying it to users. Essential for payment UIs, account pages, and audit logs.
const cardNumber = "4111222233334444";
const masked = replace(cardNumber, /\d{12}/, "************");
// => "************4444"
const email = "alice@example.com";
const maskedEmail = replace(email, /^(.{2}).*(@.*)$/, "$1***$2");
// => "al***@example.com"