You can do this with or without case sensitivity.
Unfortunately, JavaScript indexOf does not accept the locale and invariant as an argument, so you have to replace toLowerCase with toLocaleLowerCase if you want to preserve the specificity of the culture.
function replaceAll(str, find, newToken, ignoreCase) { var i = -1; if (!str) { // Instead of throwing, act as COALESCE if find == null/empty and str == null if ((str == null) && (find == null)) return newToken; return str; } if (!find) // sanity check return str; ignoreCase = ignoreCase || false; find = ignoreCase ? find.toLowerCase() : find; while (( i = (ignoreCase ? str.toLowerCase() : str).indexOf( find, i >= 0 ? i + newToken.length : 0 )) !== -1 ) { str = str.substring(0, i) + newToken + str.substring(i + find.length); } // Whend return str; }
or as a prototype:
if (!String.prototype.replaceAll ) { String.prototype.replaceAll = function (find, replace) { var str = this, i = -1; if (!str) { // Instead of throwing, act as COALESCE if find == null/empty and str == null if ((str == null) && (find == null)) return newToken; return str; } if (!find) // sanity check return str; ignoreCase = ignoreCase || false; find = ignoreCase ? find.toLowerCase() : find; while (( i = (ignoreCase ? str.toLowerCase() : str).indexOf( find, i >= 0 ? i + newToken.length : 0 )) !== -1 ) { str = str.substring(0, i) + newToken + str.substring(i + find.length); } // Whend return str; }; }
Stefan steiger
source share