In coincidence, the first character is the underscore, and the second is any character that is captured in group 1 .
In RegExp#replace() you can pass a callback method as a replacement argument. See Passing a Function as a Second Parameter :
As a second parameter, you can pass a function. In this case, the function will be executed after the matching has occurred. The result of the function call (its return value) will be used as a replacement string (note: the special replacement templates described above do not apply in this case). Note that the function will be called several times for each full match if the regular expression in the first parameter is global.
The function takes the following arguments:
match matched substring (matches the $ & replacement pattern described above).
p1, p2, ... n-th juxtaposed subgroup of the RegExp object in the first parameter of the replace() method (corresponds to the replacement patterns $1 , $2 and so on, described above). For example, if the pattern is the regular expression /(\a+)(\b+)/ , the parameter p1 will be the value of the comparison with the subgroup \a+ , and the parameter p2 - with the subgroup \b+ .
offset offset of the matched substring within the entire examined string (for example, if the entire string is 'abcd' and the matched substring is 'bc' , then this argument will be equal to 1 ).
string All the string in question.
Thus, it is possible to pass the first 2 arguments: the full text of the match and the value of the first group, and output only the changed value of the first group.
const params = [ 'field_one', 'field_two', 'justfield', 'field_three', 'longer_than_one_field' ]; const data = { fieldOne:1, fieldTwo:2, justfield:'d', fieldThree:3, longerThanOneField:'____' } console.log(params.map(key => data[key.replace(/_([az])/g, ($0,$1) => $1.toUpperCase()) ] ));
Here $0 is the full text of the match, and $1 is the value of the first group.
The expression /_([az])/ will find only those _ after which there is an ASCII letter in lower case.