Last active
April 9, 2022 05:39
-
-
Save serg06/689b1f6e76c63dfc9597d26766b31623 to your computer and use it in GitHub Desktop.
[TypeScript] Types for JavaScript's replacerFunction in String.prototype.replaceAll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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