முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 7 · பாடம் 3 இன் 4பாடத்திட்டத்தில் 27/32~12 min
தொகுதி பாடங்கள் (3/4)

திரும்ப அழைப்பதன் மூலம் மாற்றவும்

If a replacement string is not enough, pass a function: str.replace(regex, (match, ...groups) => string). The callback is invoked for every match and its return value becomes the replacement.

JS
'prezzi: 10 20 30'.replace(/\d+/g, (m) => Number(m) * 1.22);
// "prezzi: 12.2 24.4 36.6" (22% VAT)

Callback arguments

JS
str.replace(regex, (match, p1, p2, ..., offset, original, groups) => ...);
  • match -- the entire match.
  • p1, p2, \u2026 -- the captured groups in order.
  • offset -- index of the match in the original string.
  • original -- the whole string.
  • groups -- object with the named groups (if any).
JS
'2024-03-15'.replace(/(\d{4})-(\d{2})-(\d{2})/, (_, a, m, g) => `${g}/${m}/${a}`);
// "15/03/2024"

The callback gives you arbitrary power: parsing, lookup, conversion, HTML escaping\u2026 everything that a static string cannot do.

Advanced arguments in replace callbacks

The callback function receives several arguments: the full match, each captured group, the offset of the match within the whole text, and the original input string. This enables sophisticated context-based transformation logic.

Try it

உடற்பயிற்சி#regex.m7.l3.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Find every integer in the text. (In replace you would pass `(m) => Number(m) * 2` to double it.)

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Use \\d+ (one or more digits) to capture every integer as a single match.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#regex.m7.l3.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Find every email (simplified form: letters/digits/dots/underscores @ domain). This way a callback could redact it to `***@domain`.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Widen the class to [\\w.]+ to accept dots in the username and the domain.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Additional challenge

உடற்பயிற்சி#regex.m7.l3.e3
முயற்சிகள்: 0ஏற்றுகிறது…

Match every word consisting of letters in the text, so it can be transformed to uppercase via a callback.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Find simple letters with [a-zA-Z]+.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்