String.prototype.replace
Returns a new string with one or all matches of a pattern replaced by a replacement
Syntax
string.replace(pattern, replacement)Parameters
| Parameter | Type | Description |
|---|---|---|
| pattern | string | RegExp | The pattern to search for |
| replacement | string | Function | The replacement string or function |
Return Value
A new string with the replacement(s) made
Examples
const str = 'Hello World';
console.log(str.replace('World', 'JS')); // 'Hello JS'const date = '2024-01-15';
const formatted = date.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1');
console.log(formatted); // '01/15/2024'const text = 'foo bar foo';
const result = text.replace(/foo/g, 'baz');
console.log(result); // 'baz bar baz'Understanding String.prototype.replace
The String.prototype.replace method in JavaScript returns a new string with one or all matches of a pattern replaced by a replacement. It belongs to the String object and is one of the most widely used methods for working with string values in modern JavaScript and TypeScript applications.
The method signature is string.replace(pattern, replacement). It accepts 2 parameters: pattern, replacement. When called, it returns a new string with the replacement(s) made. Understanding when and how to use replace() helps you write more expressive, readable code.
Common use cases for String.prototype.replace include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like string-replaceall, string-match, string-search, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for String.prototype.replace is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
String.prototype.replaceAllReturns a new string with all matches of a pattern replaced by a replacement
String.prototype.matchRetrieves the result of matching a string against a regular expression
String.prototype.searchExecutes a search for a match between a regular expression and this string, returning the index of the first match
More String Methods
Other methods in the String object
Related Tools
More String Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.