JavaScript .replace()
Published Jun 23, 2021Updated Jun 19, 2023
Searches a string for a string value, or a regular expression, and returns a new string where some or all matches are replaced.
Syntax
string.replace(searchValue, replacementValue);
If the searchValue is a string then only the first instance of the value will be replaced. To replace all instances, use the global (g) modifier on a regular expression.
Example
Replace 'cats' with 'rats':
const weather = `It's raining cats and dogs!`;const replaceCatsWithRats = weather.replace('cats', 'rats');console.log(replaceCatsWithRats);// Output: It's raining rats and dogs!
Codebyte Example
The following is runnable and demonstrates the .replace() method using regular expressions (RegExp):
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours