return substring to the left of and including the delimiter

I have a string: “UNIT 1: LEISURE AND SPORT”

I want to extract the “UNIT 1:” part.

I was able to do that with the code below, but I’m wondering if there’s a better or more elegant of way of doing it.


set unitName to "UNIT 1: LEISURE AND SPORT"
set reducedUnitNameList to characters 1 through (offset of ":" in unitName) of unitName
set reducedUnitName to reducedUnitNameList as string

In this situation, the AppleScript Language Guide recommends the use of text rather than character to avoid the need to coerce a list to a string:

set unitName to "UNIT 1: LEISURE AND SPORT"
set reducedUnitName to text 1 through (offset of ":" in unitName) of unitName --> "UNIT 1:"

An alternative–as you are probably aware–is text item delimiters:

set unitName to "UNIT 1: LEISURE AND SPORT"
set text item delimiters to ":"
set reducedUnitName to text item 1 of unitName & ":" --> "UNIT 1:"
set text item delimiters to ""

In testing with Script Geek, the text-item-delimiter method is faster, although the difference is only one millisecond. FWIW, I would use the offset method.

Thank you. Where do you download Script Geek? I tried to download it one time, but the link was dead.

You’re welcome. Script Geek was recently moved to the Late Night Software site:

https://latenightsw.com/script-geek/