MCPcopy Create free account
hub / github.com/Rich-Harris/magic-string / _replaceRegexp

Method _replaceRegexp

src/MagicString.js:817–860  ·  view source on GitHub ↗
(searchValue, replacement)

Source from the content-addressed store, hash-verified

815 }
816
817 _replaceRegexp(searchValue, replacement) {
818 function getReplacement(match, str) {
819 if (typeof replacement === 'string') {
820 return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
821 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
822 if (i === '$') return '$';
823 if (i === '&') return match[0];
824 const num = +i;
825 if (num < match.length) return match[+i];
826 return `$${i}`;
827 });
828 } else {
829 return replacement(...match, match.index, str, match.groups);
830 }
831 }
832 function matchAll(re, str) {
833 let match;
834 const matches = [];
835 while ((match = re.exec(str))) {
836 matches.push(match);
837 }
838 return matches;
839 }
840 if (searchValue.global) {
841 const matches = matchAll(searchValue, this.original);
842 matches.forEach((match) => {
843 if (match.index != null) {
844 const replacement = getReplacement(match, this.original);
845 if (replacement !== match[0]) {
846 this.overwrite(match.index, match.index + match[0].length, replacement);
847 }
848 }
849 });
850 } else {
851 const match = this.original.match(searchValue);
852 if (match && match.index != null) {
853 const replacement = getReplacement(match, this.original);
854 if (replacement !== match[0]) {
855 this.overwrite(match.index, match.index + match[0].length, replacement);
856 }
857 }
858 }
859 return this;
860 }
861
862 _replaceString(string, replacement) {
863 const { original } = this;

Callers 2

replaceMethod · 0.95
replaceAllMethod · 0.95

Calls 1

overwriteMethod · 0.95

Tested by

no test coverage detected