Aller au contenu principal

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"