ALX
ALX

Reputation: 283

Split a string into multiple variables AppleScript

How would I turn a sentence entered by a user in AppleScript into separate variables for each word. For example, Lorem ipsum dolor sit amet would be split by the space into different variables, Ex. var1 = lorem, var2 = ipsum and so on. Below is what I've come up with so far, but I'm clearly getting nowhere.

set TestString to "1-2-3-5-8-13-21"
set myArray to my theSplit(TestString, "-")
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

Upvotes: 5

Views: 8374

Answers (1)

pbell
pbell

Reputation: 3095

Just use 'word' key word. Here is a small example of script :

set teststring to "1-2-3-5-8-13-21"
set Wordlist to words of teststring -- convert string to list of words

repeat with aword in Wordlist --loop through each word
    log aword -- do what ever you need with aword
end repeat

Upvotes: 6

Related Questions