Search code examples
javascriptapplescript

Escaping characters when running Javascript in Applescript


When using the do shell script command in AppleScript, it is often necessary to escape certain characters. Quoted form of can be used for that purpose.

Is there an equivalent designed for Applescript's do JavaScript command?

Here's an example:

set message to "I'm here to collect $100"
do shell script "echo " & message
--> error

As written, the shell script returns an error because the apostrophe ' and $ are not treated as text by the shell. The easiest and most generalizable solution is to take advantage of AppleScript's quoted form of which in one fell swoop escapes all offending characters in the message variable:

set message to "I'm here to collect $100"
do shell script "echo " & quoted form of message
--> "I'm here to collect $100"

Escaping individual occurrences of the offending characters is not a solution when the message variable changes repeatedly or is input by a lay user, etc.

The analogous situation can arise with `do JavaScript:

set theText to "I'm not recognized by Javascript because I have both
                an internal apostophe and line feed"

tell application "Safari" to do JavaScript "document.getElementById('IDgoesHere').value ='" & theText & "';" in document 1

Obviously the content of theText won't get "JavaScripted" into the intended text field because of the ' and the linefeed.

Question: Does AppleScript have an equivalent to quoted form of that is designed to "escape" text that is specifically problematic for JavaScript.


Solution

  • Applescript isn't very good with text manipulation, but you can use it to escape the characters yourself.

    You can use this subroutine from Macosxautomation.com:

    on replace_chars(this_text, search_string, replacement_string)
     set AppleScript's text item delimiters to the search_string
     set the item_list to every text item of this_text
     set AppleScript's text item delimiters to the replacement_string
     set this_text to the item_list as string
     set AppleScript's text item delimiters to ""
     return this_text
    end replace_chars
    

    Example:

    set the message_text to "I'm an apostrophe"
    set the message_text to replace_chars(message_text, "'", "'")