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.
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.
| |
Console Output
catrot
LaunchCode
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.
| |
Console Output
This example illustrates a common use case of replace, which is to remove a character by replacing it with an empty string.
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.