How to Replace All Occurrences of a String in JavaScript

How to Replace All Occurrences of a String in JavaScript

Ferenc Almasi β€’ 2021 April 07 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

In JavaScript, there are many different ways to do the same thing. Here are three different approaches to replace, or completely remove all occurrences in a string.


Using split & join

Copied to clipboard! Playground
string.replace(search).join(replacement);

// eg.:
// Returns "She sells shells by the shore"
'She sells seashells by the seashore'.split('sea').join('');
split-and-join.js

This works because the string is split into three parts using the string "sea", which results in the following array:

Copied to clipboard!
'She sells seashells by the seashore'.split('sea');// Returns:(3) ["She sells ", "shells by the ", "shore"]
split.js

This is then joined together with an empty string using join, essentially removing the string.


Using regex with replace

You can also use a regular expression, using the replace method:

Copied to clipboard!
// Return "She sells shells by the shore"
'She sells seashells by the seashore'.replace(/sea/g, '');
regex.js

Note that in order to replace every occurrence, you need to pass the global flag to the regex. Apart from the global flag, you can also use an i to indicate you want matches to be case insensitive.

Copied to clipboard!
'No lemon, no melon'.replace(/no/g, '');  // Returns "No lemon,  melon"
'No lemon, no melon'.replace(/no/gi, ''); // Returns " lemon,  melon"
regex-flags.js

Note the difference between using a case insensitive flag, and omitting it.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Using the replaceAll method

Although global support is lacking completely for IE, and older versions of other browsers, it still has relatively wide support according to caniuse.com. This can be used to quickly and easily replace, or remove all occurrences in a string without using a regex.

Copied to clipboard!
// Return "She sells shells by the shore"
'She sells seashells by the seashore'.replaceAll('sea', '');
replaceAll.js
How to Replace All Occurrences of a String in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.