JavaScript String replace() Method: A Comprehensive Guide

The replace() method in JavaScript is a powerful tool for modifying strings by replacing specific substrings or patterns with new ones. This method is essential for tasks ranging from simple text substitutions to complex data transformations. This guide covers the syntax, usage, and advanced techniques of the replace() method, providing you with the knowledge to effectively manipulate strings in JavaScript.

What is the replace() Method?

The replace() method searches a string for a specified value or a regular expression pattern and returns a new string with the replaced value. The original string remains unchanged, as strings in JavaScript are immutable.

Purpose of the replace() Method

The primary purposes of the replace() method are:

  • Replacing a specific substring with another string.
  • Replacing a matched pattern (using regular expressions) with a new string.
  • Performing global replacements to modify all occurrences of a substring or pattern.
  • Using a function to dynamically determine the replacement value based on the matched substring.

Syntax of the replace() Method

The replace() method has the following syntax:

string.replace(searchValue, replaceValue);

Parameters

Parameter Type Description
`searchValue` String or RegExp The substring or regular expression pattern to be searched for in the string.
`replaceValue` String or Function The string to replace the `searchValue` or a function to be invoked to create the new substring.

Return Value

The replace() method returns a new string with the replaced value. If the searchValue is not found, the original string is returned unchanged.

Basic Usage of replace() with Strings

The simplest use case is to replace a specific substring with another string.

const str1 = "Hello World";
const newStr1 = str1.replace("World", "JavaScript");
console.log(newStr1); // Output: Hello JavaScript

In this example, the substring "World" is replaced with "JavaScript".

Using replace() with Regular Expressions

Regular expressions provide more flexible and powerful pattern matching capabilities.

Replacing the First Match

const str2 = "Red, Blue, Red, Green";
const newStr2 = str2.replace(/Red/, "Orange");
console.log(newStr2); // Output: Orange, Blue, Red, Green

Here, the regular expression /Red/ replaces the first occurrence of "Red" with "Orange".

Global Replacement with Regular Expressions

To replace all occurrences, use the g (global) flag in the regular expression.

const str3 = "Red, Blue, Red, Green";
const newStr3 = str3.replace(/Red/g, "Orange");
console.log(newStr3); // Output: Orange, Blue, Orange, Green

The /Red/g regular expression replaces all occurrences of "Red" with "Orange".

Case-Insensitive Replacement

To perform a case-insensitive replacement, use the i (ignore case) flag in the regular expression.

const str4 = "red, Blue, Red, Green";
const newStr4 = str4.replace(/red/gi, "Orange");
console.log(newStr4); // Output: Orange, Blue, Orange, Green

The /red/gi regular expression replaces all occurrences of "red" (case-insensitive) with "Orange".

Using a Function as replaceValue

A function can be used as the replaceValue to dynamically determine the replacement value based on the matched substring.

function replaceFunc(match) {
  return match.toUpperCase();
}

const str5 = "hello world";
const newStr5 = str5.replace(/hello|world/g, replaceFunc);
console.log(newStr5); // Output: HELLO WORLD

In this example, the replaceFunc function converts each matched word to uppercase.

Function Parameters

When a function is used as the replaceValue, it can accept several parameters:

Parameter Description
`match` The matched substring.
`p1, p2, …, pn` The nth parenthesized submatch string, provided the first argument to `replace()` is a regular expression object. (Corresponds to the $1, $2, etc. replacements mentioned above.)
`offset` The offset of the matched substring within the whole string being examined.
`string` The whole string being examined.

Example with Function Parameters

function replaceFuncWithParams(match, p1, p2, offset, string) {
  return [p1, p2].join(' - ');
}

const str6 = "abc12345#$*%";
const newStr6 = str6.replace(/([^\d]*)(\d*)([^\w]*)/g, replaceFuncWithParams);
console.log(newStr6); // Output: abc - 12345

Here, the function extracts and joins the non-digit and digit parts of the string.

Advanced Techniques and Real-World Examples

Swapping Words in a String

const str7 = "John Doe";
const newStr7 = str7.replace(/(\w+)\s(\w+)/, "$2, $1");
console.log(newStr7); // Output: Doe, John

This example swaps the first and last names using capturing groups.

Converting Camel Case to Snake Case

function camelToSnake(str) {
  return str.replace(/([A-Z])/g, "_$1").toLowerCase();
}

const str8 = "camelCaseString";
const newStr8 = camelToSnake(str8);
console.log(newStr8); // Output: camel_case_string

This function converts a camel case string to snake case.

Removing HTML Tags

const str9 = "<p>This is <b>bold</b> text.</p>";
const newStr9 = str9.replace(/<[^>]*>/g, "");
console.log(newStr9); // Output: This is bold text.

This example removes all HTML tags from the string.

Formatting Phone Numbers

function formatPhoneNumber(str) {
    return str.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}

const str10 = "1234567890";
const newStr10 = formatPhoneNumber(str10);
console.log(newStr10); // Output: (123) 456-7890

This function formats a raw phone number string into a more readable format.

Use Case Example: Sanitizing User Input

Imagine you’re building a blog platform where users can submit comments. To prevent potential security vulnerabilities like cross-site scripting (XSS), you need to sanitize the user input by removing or escaping potentially harmful HTML tags and scripts. Here’s how you can use the replace() method in conjunction with regular expressions to achieve this:

function sanitizeInput(input) {
  // Remove HTML tags
  let sanitized = input.replace(/<[^>]*>/g, '');

  // Remove any script tags and their content
  sanitized = sanitized.replace(/<script\b[^<]*(?:(?!<\/script>
)<[^<]*)*<\/script>/gi, '');

  // Replace potentially harmful attributes like 'onload' or 'onerror'
  sanitized = sanitized.replace(/(onload|onerror)=["'][^"']*["']/gi, '');

  return sanitized;
}

const userInput = '<p onclick="alert(\'XSS\')">Hello, world!</p><script>alert("XSS");
</script>';
const safeInput = sanitizeInput(userInput);
console.log(safeInput); // Output: Hello, world!

In this example, the sanitizeInput function uses multiple replace() calls with regular expressions to remove HTML tags, script tags, and potentially harmful attributes. This helps to ensure that the user input is safe and does not introduce any security vulnerabilities into your application.

This use case demonstrates the importance of the replace() method in real-world scenarios where security and data integrity are critical.

Browser Support

The replace() method is supported by all modern web browsers.

Conclusion

The JavaScript replace() method is a versatile and essential tool for string manipulation. Whether you’re performing simple substring replacements or using regular expressions for complex pattern matching, replace() provides the flexibility and power you need to effectively modify strings in your JavaScript applications. By mastering the techniques outlined in this guide, you’ll be well-equipped to handle a wide range of string manipulation tasks.