Skip to content

Instantly share code, notes, and snippets.

@celsobessa
Created September 7, 2020 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsobessa/8797779ab8c0f807e855296041c10ea0 to your computer and use it in GitHub Desktop.
Save celsobessa/8797779ab8c0f807e855296041c10ea0 to your computer and use it in GitHub Desktop.
A more elegant implementation of a polyfill for replaceAll method on strings by Chris Ferdinandi (source https://vanillajstoolkit.com/polyfills/stringreplaceall/ )
/**
* String.prototype.replaceAll() polyfill
* https://vanillajstoolkit.com/polyfills/stringreplaceall/
* @author Chris Ferdinandi
* @license MIT
*/
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(str, newStr){
// If a regex pattern
if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') {
return this.replace(str, newStr);
}
// If a string
return this.replace(new RegExp(str, 'g'), newStr);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment