Am a complete newbie to this whole AppleScript thing (though used to program Basic when I was a kid and have dabbled with RealBasic in recent years) but it’s fun and rewarding - strangely satisfying when you compile a lot of lines in one go and it does it with no errors.
Anyway enough of my newbie ramblings.
I have been looking for a way to change a string (in this case a person’s name) if entered in lowercase into title case (ie. tom cruise into Tom Cruise).
The following works (and am quite pleased with myself for getting it right) but thought I’d post it here incase anyone has any ideas for streamlining it or if infact, as I suspect, there is a single command or simple series of commands that can do the same job.
set entered_text to text returned of (display dialog "enter name" default answer "")
set count_words to count words in entered_text
set word_list to words 1 through count_words of entered_text as list
set revised_text to ""
repeat with i from 1 to count_words
set this_item to item i of word_list
set ascii_number to ASCII number this_item
if ascii_number > 96 and ascii_number < 123 then -- only affect lowercase letters
set ascii_number to ascii_number - 32
set capital_letter to ASCII character ascii_number
set count_letters to count characters in this_item
if count_letters is 1 then
set revised_word to capital_letter
else
set revised_word to characters 2 through count_letters of this_item
set revised_word to revised_word as string
set revised_word to capital_letter & revised_word
end if
if i < count_words then
set revised_text to revised_text & revised_word & " "
else
set revised_text to revised_text & revised_word
end if
else
if i < count_words then
set revised_text to revised_text & this_item & " "
else
set revised_text to revised_text & this_item
end if
end if
end repeat
I remember from my old Basic days that there were commands left$, mid$ and right$ which would be a far quicker way of getting all the letters in a word bar the first one (ie a$ = right$ (this_item, len (this_item -1)) or something like that - i forget the exact syntax, it’s been over twenty years but Applescript only seems to have ‘middle’ not left or right.
I’m happy with how it works, though it only changes the first letter at the moment thus
tom cruise becomes Tom Cruise
TOM CRUISE stays as TOM CRUISE
tOM cRUISE becomes TOM CRUISE etc
though I guess I could use the same principles to change every other letter.