Replace modifier
Learn how to replace substrings or patterns in a value.
This modifier replaces a target substring or pattern with a specified replacement.
Optionally, you can specify the occurrence of the pattern to replace and the offset to start the search for more control over the replacement. And for more advanced replacements, you can even use regular expressions.
Syntax
The basic syntax for this modifier is:
/*<value>*/ replacing /*<pattern>*/ with /*<replacement>*/
To replace a specific occurrence of the pattern, use the following syntax:
/*<value>*/ replacing /*<occurrence>*/ occurrence of /*<pattern>*/ with /*<replacement>*/
You can use any ordinal to specify the occurrence, including the words first, second, third, and so on.
You can also prefix the ordinal with a definite article to make the expression more readable:
/*<value>*/ replacing the /*<occurrence>*/ occurrence of /*<pattern>*/ with /*<replacement>*/
To start the search at a specific offset, use this syntax:
/*<value>*/ replacing /*<pattern>*/ from /*<offset>*/ with /*<replacement>*/
Parameters
These are the supported parameters:
- value
The string in which to replace the pattern.
- pattern
A string or regular expression to match.
- replacement
A string to replace the matched pattern.
- occurrence(optional)
An ordinal literal indicating which occurrence of the matched pattern to replace.
Default:all occurrences- offset(optional)
A zero-based index indicating where to start the search for the pattern.
Default:starts at the beginning of the string
Examples
Here is a basic example of how to replace a substring:
"Hello World" replacing "World" with "CQL" // Hello CQL
You can replace a specific occurrence of the pattern by specifying an ordinal:
"Hello World" replacing the first occurrence of "l" with "1" // He1lo World
To replace the last occurrence, use a negative ordinal:
"Hello World" replacing the last occurrence of "l" with "1" // Hello Wor1d
For more complex replacements, you can use regular expressions:
" Hello World " replacing ~/^\s+|\s+$/ with "" // Hello World
The above example removes all leading and trailing whitespace from the string by replacing the pattern with an empty string.