How to Replace All Occurrences of a Substring in a String in TypeScript?

Recently, one of my team members asked about replacing all occurrences of a substring in a string in TypeScript. I suggested a few methods. In this tutorial, I will explain how to replace all occurrences of a substring within a string using TypeScript. Let me show you different methods with examples.

Replace All Occurrences of a Substring in a String Using TypeScript

Now, let’s explore the various methods available in TypeScript for replacing all occurrences of a substring.

Method 1: Using String.replace() with RegExp

The most common approach to replace all occurrences of a substring in a string in TypeScript is using the replace() method with a regular expression that includes the global flag.

Here is an example and the TypeScript code.

function replaceAllOccurrences(text: string, search: string, replacement: string): string {
  const regex = new RegExp(search, 'g');
  return text.replace(regex, replacement);
}

// Example usage
const originalText = "John from New York likes apples. John buys apples every week.";
const newText = replaceAllOccurrences(originalText, "John", "Mike");
console.log(newText); // "Mike from New York likes apples. Mike buys apples every week."

This approach is powerful because the replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement.

I executed the above TypeScript code using VS code, and you can see the exact output in the screenshot below:

Replace All Occurrences of a Substring in a String Using TypeScript

Caution with Special Characters

When using RegExp, you need to be careful with special characters like ., *, +, etc. These characters have special meanings in regular expressions and need to be escaped:

function replaceAllOccurrencesSafely(text: string, search: string, replacement: string): string {
  // Escape special regex characters
  const escapedSearch = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const regex = new RegExp(escapedSearch, 'g');
  return text.replace(regex, replacement);
}

// Example with special characters
const text = "The cost is $50.00. Another item costs $25.50.";
const newText = replaceAllOccurrencesSafely(text, "$", "USD ");
console.log(newText); // "The cost is USD 50.00. Another item costs USD 25.50."

Check out How to Check if a String is Empty in TypeScript?

Method 2: Using String.replaceAll() (ES2021)

If you’re using TypeScript with a modern target (ES2021 or later), you can use the replaceAll() method, which is designed specifically for replacing all occurrences:

function replaceAllWithModernMethod(text: string, search: string, replacement: string): string {
  return text.replaceAll(search, replacement);
}

// Example usage
const customerFeedback = "The service was good. The staff was good. The food was good.";
const improvedFeedback = replaceAllWithModernMethod(customerFeedback, "good", "excellent");
console.log(improvedFeedback); // "The service was excellent. The staff was excellent. The food was excellent."

This method is the simplest and best way to replace multiple occurrences of a substring in a string. It’s clean, intuitive, and doesn’t require understanding regular expressions.

Here is the exact output in the screenshot below:

TypeScript Replace All Occurrences of a Substring in a String

Browser and Environment Compatibility

One consideration with replaceAll() is browser compatibility. Make sure your TypeScript configuration targets ES2021 or later:

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2021",
    // other options...
  }
}

If you are using an older version of TypeScript that doesn’t support the replaceAll() method, you can still achieve the same result using the replace() method in combination with a regular expression.

Here’s an example:

const email = "sarah.johnson@example.com";
const modifiedEmail = email.replace(/\./g, "x");
console.log(modifiedEmail); // Output: "sarahxjohnsonx@examplexcom"

In this code, we use the replace() method with a regular expression /\./g to match all dots (.) globally in the string. The g flag ensures that all occurrences are replaced, not just the first one.

You can see the exact output in the screenshot below:

Replace All Occurrences of a Substring in a String Using TypeScript

Check out How to Check if a String is in an Enum in TypeScript?

Method 3: Using split() and join()

Another popular approach that works well even in older JavaScript environments is using split() and join() methods:

function replaceAllWithSplitJoin(text: string, search: string, replacement: string): string {
  return text.split(search).join(replacement);
}

// Example usage
const address = "123 Main St, Chicago, IL 60601";
const formattedAddress = replaceAllWithSplitJoin(address, ",", " -");
console.log(formattedAddress); // "123 Main St - Chicago - IL 60601"

Here is the exact output in the screenshot below:

How to Replace All Occurrences of a Substring in a String Using TypeScript

This approach is simple to understand and implement. It works by:

  1. Splitting the string into an array using the search string as delimiter
  2. Joining the array back together with the replacement string

Performance Considerations

For large strings or frequent replacements, the split-join method might not be the most efficient. Let’s look at a simple performance comparison:

MethodPerformanceBrowser CompatibilityCode Simplicity
RegExp replace()Medium-HighExcellentMedium
replaceAll()HighES2021+High
split()/join()MediumExcellentHigh

Read How to Split a String by Comma in TypeScript?

Method 4: Using a Helper Function with Type Safety

As a TypeScript developer, I value type safety. Let’s create a more robust helper function that combines the best of the previous methods with proper TypeScript typing:

/**
 * Replaces all occurrences of a substring in a string.
 * @param text - The original string.
 * @param search - The substring to replace.
 * @param replacement - The replacement substring.
 * @returns A new string with all occurrences replaced.
 */
function replaceAll(text: string, search: string, replacement: string): string {
  // First try the modern method if available
  if (typeof String.prototype.replaceAll === 'function') {
    return text.replaceAll(search, replacement);
  }
  
  // Fall back to RegExp approach for older environments
  const escapedSearch = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const regex = new RegExp(escapedSearch, 'g');
  return text.replace(regex, replacement);
}

// Usage examples
const email = "Please contact john.doe@example.com or support@example.com for assistance.";
const updatedEmail = replaceAll(email, "example.com", "mycompany.com");
console.log(updatedEmail);
// "Please contact john.doe@mycompany.com or support@mycompany.com for assistance."

This function provides:

  • Type safety with TypeScript
  • Fallback mechanisms for different environments
  • Special character handling
  • Clear documentation

Check out Convert an Array to a String in TypeScript

Real-World Applications

Let’s explore some practical applications of string replacement in real-world scenarios:

1. Text Sanitization

function sanitizeUserInput(input: string): string {
  // Replace potentially harmful HTML tags
  let sanitized = replaceAll(input, "<script>", "&lt;script&gt;");
  sanitized = replaceAll(sanitized, "</script>", "&lt;/script&gt;");
  
  // Normalize whitespace
  sanitized = replaceAll(sanitized, "  ", " ");
  
  return sanitized;
}

// Example with user comment
const userComment = "Great product! <script>alert('hacked')</script> Would recommend!";
console.log(sanitizeUserInput(userComment));
// "Great product! &lt;script&gt;alert('hacked')&lt;/script&gt; Would recommend!"

2. URL Parameter Formatting

function formatQueryParameters(baseUrl: string, params: Record<string, string>): string {
  let url = baseUrl;
  const queryParams: string[] = [];
  
  Object.entries(params).forEach(([key, value]) => {
    // Replace spaces with plus signs for URL compatibility
    const formattedValue = replaceAll(value, " ", "+");
    queryParams.push(`${key}=${formattedValue}`);
  });
  
  return `${url}?${queryParams.join("&")}`;
}

// Example
const searchParams = {
  q: "TypeScript string methods",
  location: "United States",
  lang: "en"
};

console.log(formatQueryParameters("https://search.example.com", searchParams));
// "https://search.example.com?q=TypeScript+string+methods&location=United+States&lang=en"

Read Convert Boolean to String in TypeScript

Advanced Techniques

Now, let me show you some advanced methods of replacing all occurrences of a substring in a string using TypeScript.

Conditional Replacement with Functions

Sometimes, you need more control over the replacement logic. The replace() method can accept a function as the second parameter:

function conditionalReplace(text: string, search: string): string {
  const regex = new RegExp(search, 'g');
  
  return text.replace(regex, (match) => {
    // Custom logic for replacement
    if (match === 'NYC') return 'New York City';
    if (match === 'SF') return 'San Francisco';
    return match;
  });
}

// Example
const cities = "I've been to NYC and SF last summer.";
console.log(conditionalReplace(cities, '(NYC|SF)'));
// "I've been to New York City and San Francisco last summer."

This approach is extremely powerful when you need different replacements based on context or specific conditions.

Case-Insensitive Replacement

For case-insensitive replacement, you can use the ‘i’ flag with RegExp:

function replaceAllCaseInsensitive(text: string, search: string, replacement: string): string {
  const escapedSearch = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const regex = new RegExp(escapedSearch, 'gi'); // 'g' for global, 'i' for case-insensitive
  return text.replace(regex, replacement);
}

// Example
const headline = "APPLE releases new iPhone. Apple fans are excited about apple products.";
console.log(replaceAllCaseInsensitive(headline, "apple", "Samsung"));
// "SAMSUNG releases new iPhone. Samsung fans are excited about Samsung products."

Performance Optimization Tips

When working with large strings or performing multiple replacements, performance becomes important. Here are some tips:

  • Cache regular expressions: If you’re using the same pattern repeatedly, create the RegExp object once and reuse it.
  • Batch replacements: When possible, combine multiple replacements into a single operation.
  • Consider string size: For very large strings, consider processing in chunks.
  • Measure performance: Use console.time() and console.timeEnd() to benchmark different approaches for your specific use case.

Conclusion

In this tutorial, I explained various methods to replace all occurrences of a substring in TypeScript.

To summarize our key methods:

  1. RegExp with replace(): Best for complex patterns and legacy support
  2. replaceAll(): Cleanest approach for modern environments
  3. split()/join(): Simple and intuitive for basic replacements
  4. Custom helper functions: For type safety and enhanced functionality

I hope this tutorial helps you!

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.