In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.
The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.
function styleHyphenFormat(propertyName) {
function upperToHyphenLower(match, offset, string) {
return (offset > 0 ? '-' : '') + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
Given styleHyphenFormat('borderTop')
, this returns 'border-top'
.
Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the toLowerCase()
method. If we had tried to do this using the match without a function, the toLowerCase()
would have no effect.
let newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());
This is because '$&'.toLowerCase()
would first be evaluated as a string literal (resulting in the same '$&'
) before using the characters as a pattern.