Replace Characters in a String Using TypeScript

In this tutorial, I will explain how to replace characters in a string using TypeScript. As a developer, you might get a requirement to modify strings by replacing specific characters or substrings. TypeScript provides several methods to do this.

Replace Characters in a String Using TypeScript

Now, let me show you how to replace characters in a string using TypeScript.

Method 1: The replace() Method

The replace() method is a built-in JavaScript method that TypeScript also uses. This method searches a string for a specified value or a regular expression and returns a new string with the specified replacements.

Here is the syntax of the replace() method:

string.replace(searchValue, replaceValue)
  • searchValue: the character or pattern to replace.
  • replaceValue: the character you want to replace it with.

Replace a Single Character

To replace a single character in a string, you can use the replace() method in TypeScript. Here’s an example:

let name = "John Doe";
let newName = name.replace("J", "D");
console.log(newName); // "Dohn Doe"

In this example, the first occurrence of “J” is replaced with “D”.

You can check out the output in the screenshot below after I executed the above TypeScript code.

Replace Characters in a String Using TypeScript

Replace All Instances of a Character

To replace all instances of a character, you can use a regular expression with the global flag (g). Here’s an example and the TypeScript code:

let name = "John Doe";
let newName = name.replace(/o/g, "a");
console.log(newName); // "Jahn Dae"

In this case, all occurrences of “o” are replaced with “a”.

Check out Convert a String to Boolean in TypeScript

Method 2: Replace All Occurrences Using replace() with RegExp

Regular expressions (regex) allow flexible pattern matching. For instance, you could match digits, special characters, or specific word patterns.

By default, replace() only changes the first match. To replace all occurrences, use a regular expression with the g flag.

Replace All Underscores

I will show you how to replace all the underscores in TypeScript. To replace all occurrences of a pattern, use the global flag (g). Here’s an example:

const city = "San_Francisco_California";
const formattedCity = city.replace(/_/g, " ");
console.log(formattedCity); // San Francisco California
  • /g is a flag for “global”, meaning all instances will be replaced.

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

TypeScript Replace Characters in a String

Check out Convert String to Number in TypeScript

Method 3: Using split() and join()

Another method to replace characters in a string in TypeScript is by using the split() and join() methods. This method is particularly useful when you need to replace all instances of a character.

const place = "Los-Angeles-California";
const newPlace = place.split("-").join(" ");
console.log(newPlace); // Los Angeles California

In this example, spaces are replaced with hyphens.

  • split("-") converts the string into an array: ["Los", "Angeles", "California"].
  • join(" ") combines them back with spaces.

It is especially helpful when working with file paths, usernames, or data from forms.

Method 4: Using a Loop to Replace Characters Conditionally

Sometimes, you only want to replace characters based on a condition. You can loop through each character and build a new string.

Replace Digits with *

Here is the complete TypeScript code to replace digits with *.

function maskPhoneNumber(phone: string): string {
  let result = "";

  for (const char of phone) {
    if (/[0-9]/.test(char)) {
      result += "*";
    } else {
      result += char;
    }
  }

  return result;
}

console.log(maskPhoneNumber("(202) 555-0191")); // (*** ) ***-****

Here is the output in the screenshot below:

How to Replace Characters in a String Using TypeScript

Read Create Multiline Strings in TypeScript

Method 5: Custom Replace Function

It is always ideal to create a reusable function. Here is how you can create a custom replace function. This function can use any logic you need to replace characters.

function customReplace(str: string, search: string, replacement: string): string {
    let result = "";
    for (let char of str) {
        if (char === search) {
            result += replacement;
        } else {
            result += char;
        }
    }
    return result;
}

let name = "Michael Johnson";
let newName = customReplace(name, "o", "e");
console.log(newName); // "Michael Jehnsen"

In this example, a custom function iterates through each character in the string and replaces “o” with “e”.

Best Practices

When working with string replacement in TypeScript, keep the following best practices in mind:

  1. Be mindful of the case sensitivity of the substrings you’re replacing. Use regular expressions with the i (case-insensitive) flag if needed.
  2. If you need to replace multiple substrings or patterns, consider using regular expressions instead of chaining multiple replace() method calls for better readability and performance.
  3. When using regular expressions, be cautious of special characters that have specific meanings in regular expressions (e.g., ^, $, *, +). Escape them with a backslash (\) if you want to match them literally.
  4. Test your string replacement code thoroughly with different input strings to ensure it behaves as expected.

Conclusion

In this tutorial, I explained how to replace characters in a string in TypeScript. I have explained various methods to replace characters, including using replace(), regular expressions, split() and join(), and custom functions. The replace() method is a simple way to replace substrings or regular expression matches with desired replacements. By using regular expressions, you can perform more advanced string replacements.

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.