Using split & join
string.replace(search).join(replacement); // eg.: // Returns "She sells shells by the shore" 'She sells seashells by the seashore'.split('sea').join('');
This works because the string is split into three parts using the string "sea", which results in the following array:
'She sells seashells by the seashore'.split('sea');// Returns:(3) ["She sells ", "shells by the ", "shore"]
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
// Return "She sells shells by the shore" 'She sells seashells by the seashore'.replace(/sea/g, '');
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.
'No lemon, no melon'.replace(/no/g, ''); // Returns "No lemon, melon" 'No lemon, no melon'.replace(/no/gi, ''); // Returns " lemon, melon"
Note the difference between using a case insensitive flag, and omitting it.
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.
// Return "She sells shells by the shore" 'She sells seashells by the seashore'.replaceAll('sea', '');
- Access exclusive interactive lessons
- Unlimited access to hundreds of tutorials
- Remove ads to learn without distractions