在 Applescript 中 运行 Javascript 时转义字符

Escaping characters when running Javascript in Applescript

在 AppleScript 中使用 do shell script 命令时,经常需要对某些字符进行转义。 Quoted form of 可用于该目的。

是否有为 Applescript 的 do JavaScript 命令设计的等效项?

这是一个例子:

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

如所写,shell 脚本 returns 出错,因为撇号 '$ 未被 shell 视为文本。最简单和最普遍的解决方案是利用 AppleScript 的 quoted form of,它一举转义 message 变量中的所有违规字符:

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

message 变量重复变化或由外行用户输入时,转义个别出现的违规字符不是解决方案。

`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

显然 theText 的内容不会 "JavaScripted" 进入预期的文本字段,因为 'linefeed

问题:AppleScript 是否有等同于 quoted form of 的设计用于 "escape" 对 JavaScript.

特别有问题的文本

Applescript 在文本操作方面不是很好,但您可以使用它自己转义字符。

您可以使用这个子程序:

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

示例:

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

(Source)