views:

969

answers:

2

I want to create a function that returns a substring of a specific string from the beginning of said string up to but not including the start of another specific string. Ideas?


So something like:

substrUpTo(theStr, subStr)

so if I inputted substrUpTo("Today is my birthday", "my"), it would return a substring of the first argument up to but not including where the second argument begins. (i.e. it would return "Today is ")

A: 

Probably a bit kludgey, but it gets the job done...

property kSourceText : "Today is my birthday"
property kStopText : "my"

set newSubstring to SubstringUpToString(kSourceText, kStopText)

return newSubstring -- "Today is "

on SubstringUpToString(theString, subString) -- (theString as string, subString as string) as string

    if theString does not contain subString then
     return theString
    end if

    set theReturnString to ""

    set stringCharacterCount to (get count of characters in theString)
    set substringCharacterCount to (get count of characters in subString)
    set lastCharacter to stringCharacterCount - substringCharacterCount

    repeat with thisChar from 1 to lastCharacter
     set startChar to thisChar
     set endChar to (thisChar + substringCharacterCount) - 1
     set currentSubstring to (get characters startChar thru endChar of theString) as string
     if currentSubstring is kStopText then
      return (get characters 1 thru (thisChar - 1) of theString) as string
     end if
    end repeat

    return theString
end SubstringUpToString
Philip Regan
Thanks so much! :)
Alexsander Akers
+4  A: 
set s to "Today is my birthday"
set AppleScript's text item delimiters to "my"
text item 1 of s
--> "Today is "
has
It probably should be noted that best practice is that the text item delimiters should be reset back to an empty string as immediately after this to avoid any possible weird errors later.
Philip Regan
Best practice is always to set TIDs to an appropriate value immediately before using text item delimiters or list-to-text coercions (both implicit and explicit). That's the only way to be sure your code isn't susceptible to errors (i.e. defensive programming).Polite practice is to store the existing TIDs in a temporary variable then restore them once you're done (i.e. the global 'text item delimiters' property in the state you found it). It's wise to do this in handlers, in case the line of code that calls the handler does something involving TIDs immediately afterwards.
has