Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.