This tutorial describes how to write a script that finds and replaces every instance of a certain substring within a string, with another string. Such a script is often needed, because no block to do this task exists in Scratch.
The script should take three parameters: a string to process, a string to be replaced, and a string to replace it with. It should output the processed string to an
Scratch provides no method for locating substrings, so the script must loop over every character in the string, and check if the current character is at the start of the substring to be replaced. If it is, it will skip to the end of the substring, and add the replacement string to the output. If it is not, it will simply add the current character to the output.
Determining whether the current character is at the beggining of the substring will itself involve looping over part of the string.
define find and replace (replaced) with (replacement) in (string) set [output v] to () set [i v] to (1) //counter repeat (length of (string)) set [j v] to (0) //another counter set [replace? v] to [true] //it begins with the assumption that it is at the start of the replaced string repeat (length of (replaced)) // it now checks if that assumption is true if <not <(letter ((j) + (i)) of (string)) = (letter ((j) + (1)) of (replaced))>> then set [replace? v] to [false] end change [j v] by (1) end if <(replace?) = [true]> then change [i v] by ((length of (replaced)) - (1)) //skip over replaced string set [output v] to (join (output) (replacement)) else set [output v] to (join (output) (letter (i) of (string))) end change [i v] by (1) end