String.prototype.replace() - JavaScript | javascript string replace
Inthisexample,alloccurrencesofcapitallettersinthestringareconvertedtolowercase,andahyphenisinsertedjustbeforethematchlocation.Theimportantthinghereisthatadditionaloperationsareneededonthematcheditembeforeitisgivenbackasareplacement.Thereplacementfunctionacceptsthematchedsnippetasitsparameter,andusesittotransformthecaseandconcatenatethehyphenbeforereturning.functionstyleHyphenFormat(propertyName){functionupperToHyphenLower(match,offset,string){return(offset?-:)+match.toLowerCase();}returnprop...
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 ? - : ) + 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()[1] method. If we had tried to do this using the match without a function, the ...