javascript - example regexp replace() method equivalent (with lastindex support)

JavaScript
[Edit]
+
0
-
0

JavaScript - example RegExp replace() method equivalent (with lastIndex support)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// Note: in the snippet you can find missing `RexExp.prototype.replace()` method equivalent that // supports `RexExp.prototype.lastIndex` property. // Hint: this approach may be used in the web borsers where 'y' flag is not working with // `String.prototype.replace()` method in the proper way (where `RexExp.prototype.lastIndex` is ignored). const replaceText = (expression, text, replacer) => { const global = expression.global; let index = 0; let result = ''; while (true) { const match = expression.exec(text); if (match === null) { break; } const entry = match[0]; result += text.substring(index, match.index); result += replacer(...match); index = match.index + entry.length; if (global === false) { break; } } result += text.substring(index, text.length); return result; }; // Usage example: const expression = /bc/g; const text = 'abcd+abcd'; console.log(replaceText(expression, text, (match) => '<--REPLACEMENT-->')); // a<--REPLACEMENT-->d+a<--REPLACEMENT-->d
Reset