在 AppleScript 中使用
do shell script
命令时,经常需要转义某些字符。 Quoted form of
可以用于此目的。
是否有为 Applescript 的
do JavaScript
命令设计的等效命令?
这是一个例子:
set message to "I'm here to collect $100"
do shell script "echo " & message
--> error
如所写,shell 脚本返回错误,因为撇号
'
和 $
不被 shell 视为文本。最简单、最通用的解决方案是利用 AppleScript 的 quoted form of
,它可以一次性转义 message
变量中的所有违规字符:
set message to "I'm here to collect $100"
do shell script "echo " & quoted form of message
--> "I'm here to collect $100"
当
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
和 '
,linefeed
的内容不会“JavaScript 化”到预期的文本字段中。
问题:AppleScript 是否有相当于
quoted form of
的工具,旨在“转义”对于 JavaScript 来说特别有问题的文本。
Applescript 不太擅长文本操作,但您可以使用它自己转义字符。
您可以使用来自 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
示例:
set the message_text to "I'm an apostrophe"
set the message_text to replace_chars(message_text, "'", "'")