--- alias: user-guide-automation-converter-stringreplace render_macros: false description: "This converter replaces text in the input string, using literal text or a regular expression" --- # String Replace The **String Replace** converter receives a string, replaces the text that matches **searchValue** with **replaceValue**, and returns the result. It follows the JavaScript `String.prototype.replace` rules: - A **searchValue** written as `/pattern/flags` is a regular expression. Add the `g` flag to replace every match; without it, only the first match is replaced. - Any other **searchValue** is literal text, and only its first occurrence is replaced. - In **replaceValue**, `$1`, `$2`, and so on insert the text captured by the matching group of the regular expression, and `$&` inserts the matched text. ## Settings | Name | Data Type | Description | | ------------ | --------- | ------------------------------------------------------------------- | | searchValue | `String` | Text to find, or a regular expression in the form `/pattern/flags` | | replaceValue | `String` | Text that replaces each match | Table 1: Settings ## Examples | Input | `searchValue` | `replaceValue` | Output | | -------------------------------- | ----------------------- | -------------- | ---------------------------------- | | `"One One"` | `One` | `Two` | `"Two One"` | | `"One One"` | `/One/g` | `Two` | `"Two Two"` | | `"Hello world"` | `legacy` | `IoT` | `"Hello world"` (no match) | | `{"first": 1234567890123456}` | `/:\s*(-?\d{16,})/g` | `: "$1"` | `{"first": "1234567890123456"}` | Table 2: Examples The last example keeps long JSON integers as text, so that they do not lose precision when the JSON is parsed. In a `Control Flow` expression, the regular expression is MathJS text, so write each backslash twice, for example `{{ stringReplace($onMessage.data, "/:\\s*(-?\\d{16,})/g", ': "$1"') }}`. See [[user-guide-automation-controller-workflow-controlflow-expressions]]. ### Invalid Input This converter fails in any of the cases below. For what happens to the rest of the chain when a converter fails (the error is logged, reported for monitoring, and the next task does not run), see [[user-guide-automation-converters-index]]. | Input | `searchValue` | Result | | ------------------------------------ | ------------------------------------------ | --------------------------------------------- | | `null` or `undefined` | Any | Fails: the input has no text to replace. | | Not a string, in a Data Flow link | Any | Fails: the input has no text to replace. | | Any string | `/pattern/flags` with an invalid pattern | Fails: the regular expression is not valid. | Table 3: Invalid Input