UNPKG

@rpearce/flexible-string-replace

Version:

🧶 Safely replace any part of a string with anything. Example: useful for replacing substrings with JSX in React

35 lines (30 loc) • 1.3 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global['fsr-umd'] = {})); }(this, (function (exports) { 'use strict'; function flexibleStringReplace(pattern, replacer, // eslint-disable-line @typescript-eslint/no-explicit-any str) { var result = []; var position = 0; str.replace(pattern, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var argsN = args.length; var match = args[0]; var originalStr = args[argsN - 1]; var charOffset = args[argsN - 2]; var prevChars = originalStr.slice(position, charOffset); var replaced = typeof replacer === 'function' ? replacer.apply(void 0, args) : replacer; result.push(prevChars, replaced); position = charOffset + match.length; return ''; // no-op }); result.push(str.slice(position)); return result; } exports.default = flexibleStringReplace; Object.defineProperty(exports, '__esModule', { value: true }); })));