AppleScript: substring index in a string

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


So something like:

substrUpTo(theStr, subStr) 

so if I enter substrUpTo("Today is my birthday", "my") , it will return the substring of the first argument to, but will not include where the second argument begins. (i.e. it will return "Today is " )

+9
function string substring methods applescript
source share
3 answers
 set s to "Today is my birthday" set AppleScript text item delimiters to "my" text item 1 of s --> "Today is " 
+9
source share

The built-in offset command should do this:

 set s to "Today is my birthday" log text 1 thru ((offset of "my" in s) - 1) of s --> "Today is " 
+4
source share

Maybe a little dumb, but it does the job ...

 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 subString then return (get characters 1 thru (thisChar - 1) of theString) as string end if end repeat return theString end SubstringUpToString 
0
source share

All Articles