简体   繁体   中英

How to remove last space text clipboard applescript?

It was:

"hello hello hello "

need

"hello hello hello"

If last characters space to remove Thank all!

get the clipboard
set the clipboard to (replacement of "1" by "2" for the result)

on replacement of oldDelim by newDelim for sourceString
    set oldTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to oldDelim
    set strtoks to text items of sourceString
    set text item delimiters of AppleScript to newDelim
    set joinedString to strtoks as string
    set text item delimiters of AppleScript to oldTIDs
    joinedString
end replacement
set the clipboard to "hello hello hello "
set theString to get the clipboard
set theWords to text from first word to last word of theString
set the clipboard to quote & theWords & quote

RETURNS:

"hello hello hello" -- with quotes


If you do not want quotes

set the clipboard to "hello hello hello "
set theString to get the clipboard
set theWords to text from first word to last word of theString
set the clipboard to theWords 

RETURNS:

hello hello hello -- without quotes

Assuming the clipboard only contains a single line of text as in your question eg "hello hello hello ", without the quotes, the following one liner removes the trailing space.

set the clipboard to text from first word to last word of (the clipboard as text)

Note: This also removes any amount leading and trailing whitespace and is unlimited in the number of words of text the single line of text on the clipboard contains.

Here's a concise method that compares the last character to a list of white space. Cleaner than a series of if or's.

-- set clipboard to "hello hello hello       "
set theString to the clipboard
repeat 99 times
    set c to last character of theString
    if c is in {tab, space, return} then
        set theString to text 1 thru -2 of theString
    else
        exit repeat
    end if
end repeat
return theString

(it's technically faster to grab "text -2 thru -1 of theString" instead of "last character", however that will ignore trailing return characters so won't work for you)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM