在 Applescript 中运行 Javascript 时转义字符

问题描述 投票:0回答:1

在 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 来说特别有问题的文本。

javascript applescript
1个回答
0
投票

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, "'", "'")
© www.soinside.com 2019 - 2024. All rights reserved.