AppleScript:删除文本字符串中的最后一个字符

3

我需要在一个文本字符串中使用AppleScript删除最后一个字符。这比我想象的要困难得多。 有人能解释一下如何实现吗?


你是否已经编写了一个获取文本字符串的脚本?如果是这样,请编辑你的问题,展示你当前的脚本。 - Michael Dautermann
4个回答

13

试试这个

set t to "this is a string"
text 1 thru -2 of t

输出:

“这是一个字符串”


5
同情。在大多数语言中,这只是一个调用内置“trim”函数的微不足道的任务,但AppleScript的库支持非常糟糕,社区也没有为填补这些空白做出任何努力,因此即使是基本的日常事务,如此类问题,你也必须自己编写特定的处理程序。例如:
on trimLastChar(theText)
    if length of theText = 0 then
        error "Can't trim empty text." number -1728
    else if length of theText = 1 then
        return ""
    else
        return text 1 thru -2 of theText
    end if
end trimLastChar

你可以考虑投资于一本AppleScript书籍(注意:我参与了Apress的合著),这些书籍通常比AppleScript自己的文档更好地涵盖了常见的文本和列表处理任务。
另一个选择是通过AppleScript-ObjC桥接调用Cocoa,从而免费获取大量可供使用的功能。虽然需要更多的工作,但对于更高级的文本处理任务,它通常是最简单、最安全、最有效的解决方案。如果/当你采取这种方式时,我建议你获取Shane Stanley的Everyday AppleScript-ObjC

1
tell application "Safari"
    open location "https://www.youtube.com/watch?v=IxnD5AViu6k#t=152.07430805"
    delay 1
end tell
delay 1

tell application "Safari"
    set theURL to URL of front document as text
end tell

repeat while theURL contains "#"
    set theURL to text 1 thru -2 of theURL
end repeat

0

我觉得这很有趣 http://applehelpwriter.com/2016/09/06/applescript-remove-characters-from-a-string/

基本上,你可以导入Foundation来帮助你

use scripting additions
use framework "Foundation"
property NSString : a reference to current application's NSString

这是我删除最后一个路径组件的方法

on myRemoveLastPath(myPath)
  set myString to NSString's stringWithString:myPath
  set removedLastPathString to myString's stringByDeletingLastPathComponent
  removedLastPathString as text
end myRemoveLastPath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接