Created
September 7, 2020 19:55
-
-
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/ )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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