Search code examples
applescript

Extract only letter characters from a string in AppleScript


Here is the example string:

"DOGE495.96"

I would like to use AppleScript to extract only "DOGE"

How would I go accomplishing this?


Solution

  • I found this method to work without having to write the entire alphabet:

    set theString to "DOGE495.96"
    set newString to ""
    
    repeat with i from 1 to count of characters in theString
        if id of character i of theString > 64 and id of character i of theString < 122 then set newString to newString & character i of theString
    end repeat
    
    return newString
    

    Output:

    "DOGE"
    

    This, however, doesn't work with diacriticals. For those, you would have to do something like this:

    set theString to "Ÿėś āńd Ñó"
    set newString to ""
    
    repeat with i from 1 to count of characters in theString
        ignoring diacriticals and case
            if "ABCDEFGHIJKLMNOPQRSTUVWXYZ" contains character i of theString then set newString to newString & character i of theString
        end ignoring
    end repeat
    
    return newString
    

    Outputs:

    "ŸėśāńdÑó"
    

    More advanced diacriticals like ß are not considered, since they count as separate characters.

    Both methods do not include whitespace, which for the lower one can easily be added, and for the upper one, the if-statement needs to be modified like this:

    if (id of character i of theString > 64 and id of character i of theString < 122) or character i of theString = space then set newString to newString & character i of theString