0

So in Javascript you have the possibility to write something along the lines of this:

let array = "This.should.be.an.array";
array = array.split(".");
console.log(array)

/* This,should,be,an,array */

Now I know that in Applescript there is:

set theText to "This should be a list"
set theList to every word of theText
return theList

{"This", "should", "be", "a", "list"}

and also:

set theText to "This
should
be
a
list"
set theList to every paragraph of theText
return theList

{"This", "should", "be", "a", "list"}

and also:

set theText to "Thisshouldbealist"
set theList to every character of theText
return theList


{"T", "h", "i", "s", "s", "h", "o", "u", "l", "d", "b", "e", "a", "l", "i", "s", "t"}

But I don't know how to split an list where there are e.g. periods between the words.

user3439894
  • 7,266
  • 3
  • 17
  • 28
gurkensaas
  • 793
  • 1
  • 5
  • 29

1 Answers1

1

I was searching for the same thing a while ago and the answer is not quite as simple. You have to use Applescript's text item delimiters. If you would want to split a string by periods you would have something like this:

set array to "This.should.be.an.array"
set AppleScript's text item delimiters to "."
set array to every text item of array
set AppleScript's text item delimiters to ""

Or written as a function it would look something like this:

on split(theString, theSplitter)
    set AppleScript's text item delimiters to theSplitter
    set theString to every text item of theString
    set AppleScript's text item delimiters to ""
    return theString
end split

Here is an approach that preserves your old Delimiters posted by Erik on erikslab.com:

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
gurkensaas
  • 793
  • 1
  • 5
  • 29