String.replace
Description
Perform a substitution within the string.
$find can be a Regex rx'...' or a string.
$replace can be a string or callback function.
'abc 123'.replace('123', 'XYZ')
//= 'abc XYZ'
// regex
'abc 123'.replace(rx'\d+', 'XYZ')
//= 'abc XYZ'
// regex - ignore case
'AbC 123'.replace(rx'abc'i, 'XYZ')
//= 'XYZ 123'
Options
| Option | Value | Description |
|---|---|---|
limit |
number | Maximum number of substitutions. |
first |
boolean | Only replace the first occurence. (Same as limit: 1) |
'aa bb aa'.replace('aa', 'XX', -first)
//= 'XX bb aa'
'abcdef'.replace(rx'\w', 'X', { limit: 4 })
//= 'XXXXef'
Capture Groups
If the pattern contains capture groups with parens (...), you can refer to them within the replacement using $1, $2, etc.
Each open paren ( is assigned a number, in the order that it appears in the pattern (including nested parens).
'abc 123'.replace(rx'(\w+) (\d+)', '$1 | $2') //= 'abc | 123'
Callback Function
If $replace is a callback function, it will be called for every match, with an argument that contains the match.
The function should return the transformed string replacement.
$fnUpper = fun ($m) {
return $m.toUpperCase()
}
'abc 123'.replace(rx'\w+', $fnUpper)
//= 'ABC 123'
// Same, but with expression notation `x{...}`
'abc 123'.replace(rx'\w+', x{ $a.toUpperCase() })
Capture Groups
If the pattern contains capture groups with parens (...), then the function will be passed a Map of submatches.
Each open paren ( is assigned a number, in the order that it appears in the pattern (including nested parens).
The key full will contain the full outer match.
$fnFormat = fun ($m) {
return $m[1].toUpperCase() ~ ' | ' ~ $m[2]
}
'abc 123'.replace(rx'(\w+) (\d+)', $fnFormat)
//= 'ABC | 123'
Replacement Count
You can call lastReplaceCount to get the number of substitutions made from the most recent call to replace.
'aa bb aa'.replace('aa', 'XX') //= 'XX bb XX'
String.lastReplaceCount() //= 2