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>*/An ordinal must be written out in the query and always counts from the first occurrence. To work the occurrence out, or to count back from the last one, write it after the keyword:
/*<value>*/ replacing occurrence /*<occurrence>*/ of /*<pattern>*/ with /*<replacement>*/Written this way, the occurrence is a zero-based index, so 0 is the first one and -1 is the last. An occurrence that falls outside the matches leaves the value unchanged.
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)
Which occurrence of the matched pattern to replace.
An ordinal literal counts from the first one. A number is a zero-based index, and a negative number counts back from the last occurrence.
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 CQLYou can replace a specific occurrence of the pattern by specifying an ordinal:
"Hello World" replacing the first occurrence of "l" with "1" // He1lo WorldTo replace the last occurrence, use a negative ordinal:
"Hello World" replacing the last occurrence of "l" with "1" // Hello Wor1dWhen the occurrence is not known upfront, use any expression that results in an integer:
"Hello World" replacing occurrence -2 of "l" with "1" // Hel1o WorldThe example above replaces the second occurrence counting back from the last one.
For more complex replacements, you can use regular expressions:
" Hello World " replacing ~/^\s+|\s+$/ with "" // Hello WorldThe above example removes all leading and trailing whitespace from the string by replacing the pattern with an empty string.