Skip to main content

$replace

$replace(string?, pattern, replacement, limit?) -> string
Compact type signature<s-(sf)(sf)n?:s>

If string is omitted, the current context value is used.

Browse categories

Source: JSONata

Documentation

Finds occurrences of pattern within str and replaces them with replacement.

It is an error if str is not a string.

The pattern parameter can either be a string or a regular expression (regex). If it is a string, it specifies the substring(s) within str which should be replaced. If it is a regex, its is used to find .

The replacement parameter can either be a string or a function. If it is a string, it specifies the sequence of characters that replace the substring(s) that are matched by pattern. If pattern is a regex, then the replacement string can refer to the characters that were matched by the regex as well as any of the captured groups using a $ followed by a number N:

  • If N = 0, then it is replaced by substring matched by the regex as a whole.
  • If N > 0, then it is replaced by the substring captured by the Nth parenthesised group in the regex.
  • If N is greater than the number of captured groups, then it is replaced by the empty string.
  • A literal $ character must be written as $$ in the replacement string

If the replacement parameter is a function, then it is invoked for each match occurrence of the pattern regex. The replacement function must take a single parameter which will be the object structure of a regex match as described in the $match function; and must return a string.

The optional limit parameter, is a number that specifies the maximum number of replacements to make before stopping. The remainder of the input beyond this limit will be copied to the output unchanged.

Examples

Mask a synthetic code value inside a note

Input

This example uses the free-text-notes example input. The expression reads the second note and masks the synthetic diagnosis code inside it.

Example input

JSON
[
" follow-up recommended in 2 weeks ",
"reports intermittent headache; DX-001 noted",
"plan PLAN-100: confirm eligibility for mbr-3001",
"lab LAB-1002 flagged as HIGH; repeat test",
"pat-0001: patient prefers morning appointments",
"normalize multiple spaces"
]

Expression

$replace($[1], /(DX-)\d{3}/, "$1###")

Result

"reports intermittent headache; DX-### noted"