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"