Version: v0.7.1 - Beta.  We welcome contributors & feedback.

String.replace

replace($find, $replace, $flags = {}) -> string

Description

Perform a substitution within the string.

$find can be a Regex r'...' or a string.

$replace can be a string or callback function.

'abc 123'.replace('123', 'XYZ')
//= 'abc XYZ'

// regex
'abc 123'.replace(r'\d+', 'XYZ')
//= 'abc XYZ'

// regex - ignore case
'AbC 123'.replace(r'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(r'\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(r'(\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 = fn ($m) {
    return $m.upperCase()
}

'abc 123'.replace(r'\w+', $fnUpper)
//= 'ABC 123'


// Same, but with expression notation `x{...}`
'abc 123'.replace(r'\w+', x{ $a.upperCase() })

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 = fn ($m) {
    return $m[1].upperCase() ~ ' | ' ~ $m[2]
}

'abc 123'.replace(r'(\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

See Also