- The characters to be replaced.
- The characters to replace it with.
In fact, the replace method is very powerful, as it allows us to switch a string or character with another string or character. Let’s take a look at a simple example.
const greeting = "Hello my name is James"; const omittedName = greeting.replace('James', '');
The example above declares a new constant, named greeting, which is of type string.
We then run the replace method on that string, which replaces the characters ‘James’ inside of the greeting constant with a blank space.
What if you had a scenario where you wanted to replace multiple instances of the name character from a string? The code example above would not replace all of the characters: ‘James’ from a string, only the first set of characters that match ‘James’.
The example code above creates a new constant variable named description (which is a description of this very site!). We then perform the replace method on it, but this time, use the global modifier in a regular expression.
This modifer, /g targets all strings inside of the description string that match the first argument.
Therefore, that data is likely going to be formatted in a particular way and may not be in the format that you want or need. That’s when you’ll need to perform some string manipulation on it.
To Perform that string manipulation you will have to use the powerful and flexible replace method. If you want to learn further string manipulation using the substring method check out this guide