ReplaceFn
ReplaceFn = (
value) =>Replacement|string
Callback function that dynamically generates replacement content based on matched text.
Parameters
Section titled “Parameters”The matched text string from the search pattern
Returns
Section titled “Returns”Either a Replacement object (for text and/or formatting changes) or a string (for simple text replacement)
Remarks
Section titled “Remarks”ReplaceFn allows you to compute replacement content dynamically for each match found
during a replace operation. The function receives the matched text as input and returns
the replacment.
This is particularly useful for:
- Transforming matched text based on its content (e.g., converting to uppercase, parsing numbers)
- Applying conditional formatting based on matched values
- Implementing complex replacement logic that depends on the match
Examples
Section titled “Examples”Transform matched text to uppercase:
// Convert all words in parentheses to uppercaseparagraph.replaceText(/\((\w+)\)/g, (match) => { return match.toUpperCase();});Apply conditional formatting based on content:
// Highlight TODO items in yellow, URGENT items in reddraft.replaceText(/\b(TODO|URGENT)\b/g, (match) => { return { text: match, formatting: { highlight: match === "URGENT" ? "#ff0000" : "#ffff00", bold: match === "URGENT" } };});Parse and transform numeric values:
// Double all numbers in the textparagraph.replaceText(/\d+/g, (match) => { const num = parseInt(match); return (num * 2).toString();});