Quirrel4.41.0

types.String.replace

Method on every string
pure string.replace(from: string, to: string): any

Returns str with every occurrence of from replaced by to.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

fromstringthe substring to find
tostringthe replacement text

Return value

A new string with every non-overlapping occurrence of from replaced by to, scanning left to right. A replacement's own text is never rescanned for further matches, so "aaa".replace("a", "aa") gives "aaaaaa", not an unbounded expansion. When from is "", str is returned unchanged rather than inserting to between every byte.

Notes

Takes exactly two arguments, both required; the VM reports the true arity here.

Example

examples/types/string/replace.nut
println("\"banana\".replace(\"an\", \"AN\") =", "banana".replace("an", "AN"))   // every occurrence, not just the first

// the inserted text is never rescanned for further matches.
println("\"aaa\".replace(\"a\", \"aa\") =", "aaa".replace("a", "aa"))

println("\"banana\".replace(\"\", \"X\") =", "banana".replace("", "X"))      // empty `from`: unchanged
Output:
"banana".replace("an", "AN") = bANANa
"aaa".replace("a", "aa") = aaaaaa
"banana".replace("", "X") = banana

See also

substSubstitutes {0}, {1}, ... and {name} placeholders in str with the given values.
splitSplits str into an array of strings.
stringclass index