Replace Character of the Text at Index X

Using AsObjC-form handler:


on replaceCharacterOfText:aText atIndex:anIndex withCharacter:aChar
	set chars to characters of aText
	set item anIndex of chars to aChar
	return chars as text
end replaceCharacterOfText:atIndex:withCharacter:

my replaceCharacterOfText:"ebc" atIndex:2 withCharacter:"a"

.
.
The same using usual AppleScript handler with positional parameters:


on replaceCharacter(aText, anIndex, aChar)
	set chars to characters of aText
	set item anIndex of chars to aChar
	return chars as text
end replaceCharacter

replaceCharacter("ebc", 2, "a")

Hi KniazidisR.

How about some explicit setting of text item delimiters before coercing the list to text? :slight_smile: Alternatively:


on replaceCharacterOfText:aText atIndex:anIndex withCharacter:aChar
	set ids to id of aText
	set item anIndex of ids to id of aChar
	return string id ids
end replaceCharacterOfText:atIndex:withCharacter:

my replaceCharacterOfText:"ebc" atIndex:2 withCharacter:"a"

There is no “fool proof” in my code. This is bad.

I can of course explicitly set AppleScript’s text item delimiters for this protection, but that would add 3 lines of code at once. And… I thought I had discovered America.

As I see it now, users are better off using the code suggested by you. It’s short, quick, and independent of the current setting of AppleScript’s text item delimiters.

What a great expression! ‘ :lol: ’