Benches macOS

4

read last 2 characters from string

apple Verified

Imported from the Apple Support Forums via the Wayback Machine 🔗

Hi, I want to read the last 2 characters from a string, the length of the string is not fixed.

Tried it with the "set xx to character 10 thru -1 of xx as string" but only get off course the character of position 10.

4 replies

Sign in or join Beachball Help to reply.

  1. 0

    Camelot

    Imported from the Apple Support Forums via the Wayback Machine 🔗

    This is an important and useful feature of AppleScript. When referencing items in a list, positive numbers work from the beginning of the list while negative numbers work from the end.

    For example, you can use 'word 1' to get the first word of a string, or 'paragraph -2' to get the penultimate paragraph.

  2. 0

    Chachi

    Imported from the Apple Support Forums via the Wayback Machine 🔗

    Hi Spencer,

    Adding to the info you've already gotten in this thread...

    Try this:

    set xx to "test string"
    set xx to text -2 through -1 of xx
    --sets xx to the text string "ng"

    or this:

    set xx to "test string"
    set xx to characters -2 through -1 of xx
    --sets xx to the list {"n", "g"}

    depending on how you need the characters returned to you in your script.

    Hope this helps...

  3. 0

    Jacques Rioux

    Imported from the Apple Support Forums via the Wayback Machine 🔗

    Hello.

    -2 are the last two characters in the string.

    set xx to text -2 thru -1 of xx

  4. 0

    Spencer Lips1

    Imported from the Apple Support Forums via the Wayback Machine 🔗

    Hi thanx, that did the trick, it's all so easy as you see the answer.