ModelWorks logoModelWorks
JSON TransformString

replace

Replace the first occurrence of a substring

replace

Replaces the first occurrence of pattern with replacement in a string. To replace every occurrence, use replaceAll.

Options

OptionTypeRequiredDefaultDescription
patternstringYesLiteral substring to find.
replacementstringYesSubstring to insert in place of the match.

Example

Input

JSON
"foo bar foo"

Operation

JSON
{ "type": "replace", "options": { "pattern": "foo", "replacement": "qux" } }

Output

JSON
"qux bar foo"

In a Circuit Step

JSON
{
  "name": "rewrite_first_token",
  "description": "Replace the first occurrence of `foo` in the input",
  "function": "circuit.core.transform.json",
  "input": {
    "source": "${{ input.text }}",
    "operations": [
      { "type": "replace", "options": { "pattern": "foo", "replacement": "qux" } }
    ]
  },
  "outputs": [
    {
      "name": "rewritten_text",
      "description": "Input text with the first `foo` replaced by `qux`",
      "value": "${{ rewrite_first_token.output.transformed_result }}"
    }
  ]
}

Notes & gotchas

  • Errors with replace: expected string if the input is not a string.
  • pattern is treated as a literal substring, not a regex.
  • If pattern is not found, the original string is returned unchanged.
  • For all-occurrences semantics, use replaceAll.
On this page

On this page