window.ENTITIES={'/api/snippets/javascript/javascript%20-%20example%20regexp%20replace()%20method%20equivalent%20(with%20lastindex%20support)':[{"result":true,"message":null,"batch":{"type":"javascript","name":"javascript - example regexp replace() method equivalent (with lastindex support)","items":[{"id":"pJZm7p","type":"javascript","name":"JavaScript - example RegExp replace() method equivalent (with lastIndex support)","content":"// ONLINE-RUNNER:browser;\n\n// Note: in the snippet you can find missing `RexExp.prototype.replace()` method equivalent that\n// supports `RexExp.prototype.lastIndex` property.\n\n// Hint: this approach may be used in the web borsers where 'y' flag is not working with\n// `String.prototype.replace()` method in the proper way (where `RexExp.prototype.lastIndex` is ignored).\n\nconst replaceText = (expression, text, replacer) => {\n const global = expression.global;\n let index = 0;\n let result = '';\n while (true) {\n const match = expression.exec(text);\n if (match === null) {\n break;\n }\n const entry = match[0];\n result += text.substring(index, match.index);\n result += replacer(...match);\n index = match.index + entry.length;\n if (global === false) {\n break;\n }\n }\n result += text.substring(index, text.length);\n return result;\n};\n\n\n// Usage example:\n\nconst expression = /bc/g;\nconst text = 'abcd+abcd';\n\nconsole.log(replaceText(expression, text, (match) => '<--REPLACEMENT-->')); // a<--REPLACEMENT-->d+a<--REPLACEMENT-->d","source":"","author":{"id":"xaOq10","name":"ArcadeParade","avatar":"1629138213061__xaOq10__w40px_h40px.jpg","points":666,"role":"BASIC"},"creationTime":1704461397000,"updateTime":1718920226000,"removalTime":null}]}}]};