AppleScript: How to split a string

I think of AppleScript as a fantasic tool to automate things in OS X. But, people—like me—being used to the likes of Perl, Ruby or Python miss the split()-function.

A short explanation regarding split(): The function allows the programmer (a.k.a. us) to translate a string like ‘A-B-C-D’ into a character array, using (in this case) - as delimiter, or marker where data ends or begins during the translation.

Back to AppleScript, there is no function to split a string easily; the “whys” seem to be buried in the vaults of the developers. Not that we wouldn’t need that kind of functionality on a recurring basis, though. 😉 But since AppleScript has a property called text item delimiters, we could make use of said property, couldn’t we? Let’s take a look at the code first:


	set myTestString to "1-2-3-5-8-13-21"

	set myArray to my theSplit(myTestString, "-")

	on theSplit(theString, theDelimiter)
		-- save delimiters to restore old settings
		set oldDelimiters to AppleScript's text item delimiters
		-- set delimiters to delimiter to be used
		set AppleScript's text item delimiters to theDelimiter
		-- create the array
		set theArray to every text item of theString
		-- restore the old setting
		set AppleScript's text item delimiters to oldDelimiters
		-- return the result
		return theArray
	end theSplit

The first two lines make use of the handler and display the result in the, appropriately named, “Result”-window in Script Editor.app. The Handler theSplit expects a string and the delimiter to be used as arguments. We need to store the current setting of text item delimiters first. (Never ever override the delimiter without restoring it as soon as you are done, debugging of larger scripts can be a real pain should you forget to restore, believe me.) Then we override the current setting with our delimiter. The theArray is populated with the split-up contents of theString, the delimiter is restored and we return the result.

I’m aware that I could have just used theString and overwrite it with the result, but doing it this way allows the insertion of another handler to convert the array to a different data-type, if needed. 😉

The other thing I’m aware of is the fact, that the code shown above ruins my XHTML-conformity for good, a sacrifice for you, dear reader. :mrgreen:

3 Comments

  1. Brian
    Posted July 6, 2014 at 8:34 am | Permalink

    You are my hero. That is all.

  2. Posted August 12, 2014 at 5:27 pm | Permalink

    Thanks. 😉

  3. Razor
    Posted October 6, 2014 at 1:46 pm | Permalink

    Works perfect! HUGE thanks!

Post a Comment

Your email is never published nor shared. Required fields are marked *, comments are moderated.

*
*