5.7. Locating Strings inside Strings

Sometimes you want to see if a string contains another string. For example, you might want to see if a file contains a JPEG image by testing if the file name ends with the characters .jpg. Or you might want to see if a POSIX path specifies a full path by testing if it begins with a / character. Finally, you might want to locate the occurrence of a particular string inside some text, perhaps to delete or change it to something else.

You saw in Chapter 3 how you could use the operators comes before (or <) and comes after (or >) to test how two strings are ordered. AppleScript also provides operators, called containment operators, that let you test whether one string begins with another string, ends with another string, or contains another string. The offset command lets you determine precisely where within one string another string occurs.

The containment operators and the offset command are summarized in the following table.

Operator or CommandMeaningExamples
s1 begins with s2Does string s1 begin with string s2?"iTunes Library" begins with "iTunes"
s1 ends with s2Does string s1 end with string s2?"Macintosh HD:Users:" ends with ":"
s1 contains s2Does string s2 occur in string s1?theText contains "AppleScript"
s1 does not contain s2Does string s2 not occur is string s1?theText does not contain "Cocoa"
s1 is in s2oes string s1 occur in string s2? D"AppleScript" is in theText
s1 is not in s2Does string s1 not occur in string s2?"Cocoa" is not in theText ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.