---
title: "String.prototype.replace You Might Have Missed"
description: "Using replacer functions in JavaScript’s String.replace method. Practical notes and code examples on — Scribe notes."
url: "https://h3manth.com/scribe/string-prototype-replace-you-might-have-missed/"
canonical_url: "https://h3manth.com/scribe/string-prototype-replace-you-might-have-missed/"
markdown_url: "https://h3manth.com/scribe/blog/string-prototype-replace-you-might-have-missed.md"
publishDate: "2016-01-10T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript"]
word_count: 101
reading_time_minutes: 1
x_markdown_tokens: 272
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# String.prototype.replace You Might Have Missed

> Using replacer functions in JavaScript’s String.replace method. Practical notes and code examples on — Scribe notes.

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

```javascript
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!
