用苹果脚本替换文件名中的空格以传递到剪贴板



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

我已经使用了堆栈溢出上其他地方建议的替换空格代码结构,但代码出现了错误 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/

感谢您提供的任何帮助。

迈克尔

不确定 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

以下是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

相关内容

  • 没有找到相关文章

最新更新