Very necessary edit, please use this:
subreplace("212211", "11", "", 1)
on subreplace(varstring, varold, varnew, varreps)
try
if varstring is in {null, missing value} then error
set varstring to varstring as string
on error
error "subreplace: String parameter should not or cannot be coerced to type string."
end try
set varold to varold as list
set varnewold to {}
repeat with varitem in varold
if varitem is in {null, missing value, ""} then
if varitem as string is "" then set varitem to "\"\""
error "subreplace: Removal parameter item (" & varitem & ") should not or cannot be coerced to type string"
end if
try
set varnewold to varnewold & (varitem as list as string)
on error
try
error "o" & varitem & "o"
on error varerr
error ("subreplace: Removal parameter item (" & characters 12 thru -25 of varerr as string) & ") should not or cannot be coerced to type string"
end try
end try
end repeat
set varold to varnewold
if varnew is not in {null, missing value} then
try
set varnew to varnew as string
on error
error "subreplace: Replacement parameter should not or cannot be coerced to type string."
end try
end if
try
set varreps to varreps as boolean
on error
error "subreplace: Repeated parameter should not or cannot be coerced to type boolean"
end try
set varline to characters of varstring as list
set varnewline to {}
set varnewword to ""
repeat with varlet in varline
set varlet to varlet as string
if varlet is not in varold then
set varnewword to varnewword & varlet
else
if varnewword is not "" then
if varnew is in {null, missing value} then
set varnewline to varnewline & varnewword as list
set varnewword to ""
else
set varnewline to varnewline & varnewword & varnew as list
set varnewword to ""
end if
else
if varreps is true and varnew is not in {null, missing value} then
set varnewline to varnewline & varnew as list
end if
end if
end if
end repeat
if varnewword is not "" then set varnewline to varnewline & varnewword as list
return varnewline
end subreplace
Parameters:
varstring -your string [string]
varold -items to replace (“” does not work) [string or list of strings (others will try to be coerced to string)]
varnew -string to replace with, specify null to return no replacement value, specifying “” uses “” as replacement items [string or null/missing value]
varreps -whether you want back to back replacement items to be treated individually or not [boolean (inc. 0 and 1)] e.g. subreplace(“2/1 3/2 1 2/2 2 && & 5 2/10”, {" ", “&”}, “hi”, true) returns {“2/1”, “hi”, “3/2”, “hi”, “1”, “hi”, “2/2”, “hi”, “hi”, “hi”, “hi”, “2”, “hi”, “hi”, “hi”, “hi”, “hi”, “hi”, “hi”, “5”, “hi”, “2/10”} but false returns {“2/1”, “hi”, “3/2”, “hi”, “1”, “hi”, “2/2”, “hi”, “2”, “hi”, “5”, “hi”, “2/10”}
Return value: a list of strings, therefore use ‘as string’ for the string, I didn’t want to default this incase someone had a use for the list.