Skip to content

Instantly share code, notes, and snippets.

@serg06
Last active April 9, 2022 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serg06/689b1f6e76c63dfc9597d26766b31623 to your computer and use it in GitHub Desktop.
Save serg06/689b1f6e76c63dfc9597d26766b31623 to your computer and use it in GitHub Desktop.
[TypeScript] Types for JavaScript's replacerFunction in String.prototype.replaceAll
export interface ReplacerArgs {
match: string; // the matched substring
groups: string[]; // captured groups
offset: number; // offset of match
string: string; // entire string
named_groups?: Record<string, string>; // named capturing groups
}
function parseReplacerArgsMutating(args: [string, ...any[]]): ReplacerArgs {
const named_groups = typeof args[args.length - 1] === 'object' ? (args.pop() as Record<string, string>) : undefined;
const string = args.pop() as string;
const offset = args.pop() as number;
const match = args[0];
const groups = args.slice(1) as string[];
return {match, groups, offset, string, named_groups};
}
export function parseReplacerArgs(args: [string, ...any[]]): ReplacerArgs {
return parseReplacerArgsMutating([...args]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment