替换filename中的空格以使用applescript传递给剪贴板

时间:2014-02-10 22:31:40

标签: text replace applescript

我正在编写一个脚本,让Finder在本地获取文件的位置,用%20替换空格,然后追加localhost://,这样转换后的文件名就可以插入到电子邮件中。

我已经使用了stackoverflow上其他地方建议的替换空格代码结构,但是代码出现了错误1721.我不确定我做错了什么。

文本替换的代码是:

on run {input, parameters}
    set newString to {"localhost://"}
    set aString to "/file name input/"
    set aString to aString as text
    set charToReplace to " "
    set newChar to "%20"
    repeat with i in aString
        if (i as string) is charToReplace then
            set end of newString to newChar
        else
            set end of newString to (i as string)
        end if
    end repeat
    return input
end run

输出应为/ file%20name%20input /

感谢您提供的任何帮助。

迈克尔

2 个答案:

答案 0 :(得分:0)

不确定1721错误,但这是字符串搜索和替换的替代方法。

它使用AppleScript的text item delimiters。我认为这种技术类似于split()。join()方法来替换JavaScript中的文本。

    set aString to "/file name input/"
    set my text item delimiters to " "
    set split_list to every text item of aString -- split in to list of everything between the spaces
    set my text item delimiters to "%20"
    set newString to (split_list as text) -- join, using the %20 as the delimter
    set newString to "localhost://" & newString -- prepend your protocol string

答案 1 :(得分:0)

以下是Applescript的搜索和替换子例程的标准版本:

set encodedString to searchAndReplace(aString, space, "%20")

on searchAndReplace(myString, oldText, newText)
    set AppleScript's text item delimiters to oldText
    set myList to text items of myString
    set AppleScript's text item delimiters to newText
    set myString to myList as string
    set AppleScript's text item delimiters to ""
    return myString
end searchAndReplace