Applescript: extracting "up to" x chars of a string

Discussion in 'Mac Programming' started by cricketbird, Dec 12, 2011.

  1. cricketbird macrumors member

    Feb 17, 2008
    I have a string that I want to use as a filename when saving a document. However, the string varies in length (up to several thousand words), so I want to cut it down to something more reasonable.

    I have this, which correctly uses just the first 100 characters as the filename:

    set myTitle to text 1 thru 100 of myLongString
    	make new document
    	set text of document 1 to otherStuff
    	save document 1 to "/Users/Me/Desktop/" & myTitle & ".html"
    This works fine whenever myLongString is more than 100 characters long. However, it spits back an error if it is shorter. How can I save my file as "up to" the first 100 chars of myLongString?

  2. Partron22 macrumors 68020


    Apr 13, 2011
    -- comment out one of the lines below to see how the code handles the other:
    set myLongString to "Frozen pizza and chickpeas"
    set myLongString to "The following normative documents contain provisions which, through reference in this\rtext, constitute provisions of this International Standard."
    if length of myLongString is less than 100 then
    	set myTitle to myLongString
    	set myTitle to text 1 thru 100 of myLongString
    end if
  3. cricketbird thread starter macrumors member

    Feb 17, 2008
    Thanks Partron22! It's so simple once the answer is in front of me. *sheepish*

Share This Page