Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 4, 2019 17:28
Show Gist options
  • Save masautt/c27efdded65c976f7dc19cef9c6a8e2c to your computer and use it in GitHub Desktop.
Save masautt/c27efdded65c976f7dc19cef9c6a8e2c to your computer and use it in GitHub Desktop.
How to replace all occurrences of a string in JavaScript?
// Using RegEx
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
// Split and Join (Functional Implementation)
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment