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

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

  1. macrumors member

    Joined:
    Feb 17, 2008
    #1
    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:

    Code:
    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?

    Thanks,
    CB
     
  2. macrumors 65816

    Partron22

    Joined:
    Apr 13, 2011
    #2
    Code:
    -- 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
    else
    	set myTitle to text 1 thru 100 of myLongString
    end if
     
  3. thread starter macrumors member

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

Share This Page