fast-replaceall
Version:
Replace all substring matches in a string.
59 lines (58 loc) • 2.22 kB
JavaScript
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.fastReplaceall = factory());
})(this, function() {
"use strict";
function fitIndex(fromIndex, length) {
return fromIndex ? fromIndex < 0 ? Math.max(0, length + fromIndex) : Math.min(fromIndex, length - 1) : 0;
}
function processBlankSegment(str, replacement, isFn, index) {
return isFn ? replacement("", index, str) : replacement;
}
function handleZeroLengthEdgeCase(str, len, replacement, isFn) {
var result = "".concat(processBlankSegment(str, replacement, isFn, 0));
for (var i = 0; i < len; i++) {
result += str[i] + processBlankSegment(str, replacement, isFn, i + 1);
}
return result;
}
function replaceAll(str, substr, replacement, options) {
if (typeof str !== "string") {
return str;
}
if (typeof substr !== "string") {
return str;
}
var isFn = typeof replacement === "function";
var substrLen = substr.length;
var totalLen = str.length;
if (substrLen === 0) {
return handleZeroLengthEdgeCase(str, totalLen, replacement, isFn);
}
var _a = options || {}, fromIndex = _a.fromIndex, caseInsensitive = _a.caseInsensitive;
var currentIndex = fitIndex(fromIndex, totalLen);
var searchStr = substr;
var sourceStr = str;
if (caseInsensitive) {
searchStr = substr.toLowerCase();
sourceStr = str.toLowerCase();
}
var result = "";
var lastIndex = 0;
while (currentIndex <= totalLen - substrLen) {
var matchIndex = sourceStr.indexOf(searchStr, currentIndex);
if (matchIndex === -1) {
break;
}
result += str.slice(lastIndex, matchIndex);
if (isFn) {
result += replacement(str.slice(matchIndex, matchIndex + substrLen), matchIndex, str);
} else {
result += replacement;
}
lastIndex = matchIndex + substrLen;
currentIndex = lastIndex;
}
return lastIndex === 0 ? str : result + str.slice(lastIndex);
}
return replaceAll;
});