The replace method signature: replace(regexp|substr, newSubStr|function[, flags])
The replacer function receives:
match- The matched substringp1, p2...pn- Parenthesized submatch stringsoffset- Offset of the matched substringstring- The entire string
Example: Double Values
function replacer(match) { return 2 * match; }
'10 gms protein and 5gms fat'.replace(/[0-9]+/g, replacer);
// '20gms protein and 10gms fat'
## Example: Fahrenheit to Celsius
javascript
function f2c(temp) {
function convert(match, p1) {
return ((p1 - 32) * 5/9) + 'C';
}
return temp.replace(/(-?\d+(?:\.\d*)?)F\b/g, convert);
}
f2c('212F'); // '100C'
Using replacer functions can avoid explicit loops!
#javascript
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.