Replace a character in a string

I found a very nice script which saves emails from Entourage into a folder but I need to make it more error free. The script doesn’t contain any code which would change unwanted characters into something else, for example, an “/”. The script saves the name of the email into a string, this is where I would like to change the character “/” for a “-”. Any ideas will be appreciated. Thanks!

Hi,

if only one character has to be replaced, text item delimiters is your friend

set a to "I/don't/like/slahes"
set {TID, text item delimiters} to {text item delimiters, "/"}
set a to text items of a
set text item delimiters to "-"
set a to a as string
set text item delimiters to TID
a --> I-don't-like-slahes

if there are more, you can use a repeat loop with a list to change the text item delimiters


property charList : "/{}[]"

set theText to "asd/hf{lkj}h[f]ljhjh"
set TID to text item delimiters
repeat with i in charList
	set text item delimiters to i
	set theText to text items of theText
	set text item delimiters to "-"
	set theText to theText as string
end repeat
set text item delimiters to TID
theText --> asd-hf-lkj-h-f-ljhjh

or parse the text character by character

property charList : "/{}[]"

set theText to "asd/hf{lkj}h[f]ljhjh"
set newText to ""
repeat with i in (get characters of theText)
	if i is in charList then
		set newText to newText & "-"
	else
		set newText to newText & i
	end if
end repeat
newText --> asd-hf-lkj-h-f-ljhjh

Got it, worked great. Thanks for your suggestions!:smiley:

See also: str_replace()