Publishers of technology books, eBooks, and videos for creative people

Home > Blogs > Using AppleScript to work with text, Five AppleScript Tips in Five Days

Using AppleScript to work with text, Five AppleScript Tips in Five Days

AppleScript comes with many built-in objects and commands for reading and manipulating text. Most scriptable word-processing applications include similar objects and commands along with additional objects and commands for complex scripting scenarios. But for basic text manipulation, you can use AppleScript's built-in features without telling an application to help you out.

One of AppleScript's very useful text-manipulation features is the built-in 'text item delimiters' variable. Normally, you use this variable with text files containing lists. You set 'AppleScript's text item delimiters' to whatever character is used as an item separator in the target text, such as a comma, colon or forward slash character. Then, when you ask for the 'text items' of the target text, AppleScript returns an AppleScript list object containing each of the items. Your script can use a 'repeat' loop to perform work on each of the resulting items in turn. Here's a simple example that returns every word in a short string using the space character as a delimiter.

   set AppleScript's text item delimiters to space
   set these_items to the text items of "5551234 SMITH WILLIAM J"
   --> returns: {"5551234", "SMITH", "WILLIAM", "J"}

You can click this link to open the script in the Script Editor window: Script 17.38

You can use this feature of AppleScript to accomplish much more interesting tasks. Today's tip is an example that uses text item delimiters in a subroutine handler that could act as the engine of an AppleScript form letter generator.

   set this_greeting to "Thank you [[CUST]] for trying our products!"
   set this_greeting to replace_text(this_greeting, "[[CUST]]", "Bob")
   --> returns: "Thank you Bob for trying our products!"

   on replace_text(this_text, search_string, replacement_string)
      set AppleScript's text item delimiters to the search_string
      set the item_list to every text item of this_text
      set AppleScript's text item delimiters to the replacement_string
      set this_text to the item_list as string
      set AppleScript's text item delimiters to {""}
      return this_text
   end replace_text

Click this link to open the script in the Script Editor window: Script 17.44

These two scripts are Script 17.38 and Script 17.44 in our book Apple Training Series: AppleScript 1-2-3. Read Chapter 17 for more useful information about working with text in AppleScript.

To learn more about AppleScript, such as how to script applications that are not scriptable by design, return to this blog each day this week for new tips from our book Apple Training Series: AppleScript 1-2-3.