Know that you can use a transformer function as a second parameters if you need to transform and manipulate the capture groups ...
API
replace(
regex,
(matched, capture1, capture2, /*...,*/ capture_n, index, input_str) => transformed(/*...*/)
)
replace(
regex: Regex,
transformer: (matched: string, capture1: string, capture2: string, /*...,*/ capture_n: string, index: number, input_str: string) => string
) => string
The number of captures is relative to how much did you use in your regex. index
and input_str
are the last ones.
see the examples below and their output to get a better idea about what is each.
Doc ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#making_a_generic_replacer
Examples:
// To uses example
const propsArgs = args.map((arg) =>
arg.slice(2).replace(/-(.)/g, (matched, captureGroup, index, input) => {
return captureGroup.toUpperCase();
})
);
// To uses example multiple captures groups
const propsArgs = args.map((arg) =>
arg
.slice(2)
.replace(/-(.)(.)/g, (matched, capture1, capture2, index, input) => {
return capture2.toUpperCase();
})
);
// To uses example multiple captures groups args destructuring version
// args[0] matched, args[1] capture 1, ....., args[n] capture n, args[n+1] index, args[n+2] total string to replace.
const propsArgs = args.map((arg) =>
arg.slice(2).replace(/-(.)(.)/g, (...args) => {
return args[2].toUpperCase(); // capture 2
})
);
// example for understanding
const propsArgs = args.map((arg) =>
arg.slice(2).replace(/-(.)/g, (...args) => {
console.log(args); // [ '-f', 'f', 6, 'config-file' ]
return args[1].toUpperCase();
})
);
// multiple capture groups and the args order
/**
* matched string, then all the captures arg after another, then index, then total input string to replace
*/
const propsArgs = args.map((arg) =>
arg
.slice(2)
.replace(
/-(.)(.)(.)/g,
(matched, capture1, capture2, capture3, index, input) => {
// [ '-wat', 'w', 'a', 't', 3, 'log-watch-compilation' ]
return capture1.toUpperCase();
}
)
);
The core example from above was to convert the command lines args to the javascript camel case equivalent.
Transforming this:
[
'--filename',
'--config-file',
'--env-name',
'--no-swcrc',
'--ignore',
'--only',
'--watch',
'--quiet',
'--source-maps',
'--source-map-target',
'--source-file-name',
'--source-root',
'--out-file',
'--out-dir',
'--copy-files',
'--include-dotfiles',
'--config',
'--sync',
'--log-watch-compilation',
'--extensions'
]
to
[
'filename', 'configFile',
'envName', 'noSwcrc',
'ignore', 'only',
'watch', 'quiet',
'sourceMaps', 'sourceMapTarget',
'sourceFileName', 'sourceRoot',
'outFile', 'outDir',
'copyFiles', 'includeDotfiles',
'config', 'sync',
'logWatchCompilation', 'extensions'
]