replace Examples

The general syntax for this method is:

stringName.replace(searchChar, replacementChar);

Given a search string searchChar and a replacement value replacementChar, this method returns a copy of stringName with the first occurrence of searchChar replaced by replacementChar.

Note

The replace method can be used in more powerful ways utilizing regular expressions. We will not cover those here, but you can read more at MDN.

Example
1
2
3
console.log("carrot".replace("r", "t"));

console.log("Launch Code".replace(" ", ""));

Console Output

catrot
LaunchCode
Example

Some email providers, including Gmail, allow users to put a . anywhere before the @ symbol. This means that [email protected] is the same as [email protected].

Remove the . before the @ symbol in an email address.

1
2
3
let input = "[email protected]";
let email = input.replace(".", "");
console.log(email);

Console Output

This example illustrates a common use case of replace, which is to remove a character by replacing it with an empty string.

Warning

Notice in the last example that if there is not a . before the @ symbol, the . that is part of the domain, launchcode.org would be inadvertently removed. In a real application, we would want to isolate the portion in front of @ using slice.