Hemanth's Scribes

javascript

String.prototype.replace You Might Have Missed

Author Photo

Hemanth HM

Thumbnail

The replace method signature: replace(regexp|substr, newSubStr|function[, flags])

The replacer function receives:

  • match - The matched substring
  • p1, p2...pn - Parenthesized submatch strings
  • offset - Offset of the matched substring
  • string - 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
Author Photo

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.