Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 228
ALX Avatar asked Feb 09 '17 02:02

ALX


People also ask

How to split a string into multiple strings in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can you split a string into an array?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.

How split a string in Linux?

Split without $IFS variable In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.


1 Answers

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
like image 159
pbell Avatar answered Sep 20 '22 20:09

pbell