This tutorial describes how to write a script that finds and replaces every instance of a certain substring within a string, with another string.

An example implementation can be found here.

Script

This script requires three variables:

  • (i) — the primary loop variable
  • (j) — the secondary loop variable
  • (output) — the output string
define replace (substring) with (replacement) in (string)
set [output v] to []
set [i v] to (1)
set [j v] to (1)
repeat until <<(i) > (length of (string))> and <(j) = (1)>>
    if <(letter (i) of (string)) = (letter (j) of (substring))> then
        change [j v] by (1)
        if <(j) > (length of (substring))> then
            set [output v] to (join (output) (replacement))
            set [j v] to (1)
        end
    else
        if <(j) > (1)> then
            change [i v] by ((1) - (j))
        end
        set [output v] to (join (output) (letter (i) of (string)))
        set [j v] to (1)
    end
    change [i v] by (1)
end

See Also