replace()

ES3+

Returns a new string with some or all matches of a pattern replaced by a replacement.

Syntax

string.replace(searchValue, replaceValue)

Parameters

searchValue string | RegExp

The value to search for

replaceValue string | Function

The replacement string or function

Return Value

string

A new string with replacements made

Examples

JavaScript
const str = 'Hello World';
console.log(str.replace('World', 'JavaScript'));
console.log(str.replace(/o/g, '0'));
Output:
// 'Hello JavaScript' 'Hell0 W0rld'

📌 When to Use

Use replace() for single occurrence replacements, pattern-based transformations with regex, or when you need a replacement function for complex logic. It is the most versatile string transformation method.

⚠️ Common Mistakes

Expecting replace() to replace ALL occurrences with a string pattern - without the /g flag or using a string, only the first match is replaced.

Not escaping special regex characters when using a dynamic pattern - characters like . * + ? need to be escaped.

Forgetting that $ has special meaning in the replacement string ($1, $2 for capture groups, $& for matched text).

✅ Best Practices

Use replaceAll() for simple global string replacements in modern code instead of replace() with /g flag.

Use a function as the second argument for complex transformations where each match needs different processing.

When building regex from user input, always escape special characters to prevent regex injection.

⚡ Performance Notes

replace() with a function callback is slower than a simple string replacement due to function invocation overhead. For repeated replacements on large texts, consider if split/join might be more efficient. Regex compilation can be optimized by storing the RegExp object outside loops.

🌍 Real World Example

Template Processing and Text Transformation

replace() is essential for template engines, sanitizing user input, formatting data for display, and transforming text based on patterns.

// Simple template variable replacement
function processTemplate(template, data) {
  return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
    return data[key] !== undefined ? data[key] : match;
  });
}

const template = 'Hello, {{name}}! You have {{count}} messages.';
const data = { name: 'John', count: 5 };
console.log(processTemplate(template, data));
// Output: 'Hello, John! You have 5 messages.'

// Sanitize HTML to prevent XSS
function escapeHtml(text) {
  const escapeMap = {
    '&': '&',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return text.replace(/[&<>"']/g, char => escapeMap[char]);
}

console.log(escapeHtml('<script>alert("xss")</script>'));
// Output: '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'

// Convert camelCase to kebab-case
function toKebabCase(str) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

console.log(toKebabCase('backgroundColor')); // 'background-color'

Related Methods