Ace Ace
Ace Ace

Reputation: 57

Applescript: copy the selected text and assign it to a var. Then replace the spaces inbetween with -

Here's a screenshot of my Mouse Gesture App. I right-click and draw a gesture with my mouse, the app can execute an AppleScript that I put in the right-bottom box.

The scenario for the script is that:


If you have other better way, that would be great.


  1. After getting the word, edit it by replacing spaces in between with "-" dashes.

                   i.e.   "hook up"  -->  "hook-up"
    
  2. Then open a new tab in Chrome where URL is : https://dictionary.cambridge.org/dictionary/english-chinese-simplified/hook-up Here "hook-up" should be the selected keyword

enter image description here

script generated by ChatGPT, but it doesn't work.

set theText to (the clipboard as text)

set theText to replace_spaces(theText)

set theURL to "www.dictionary.com/" & theText

tell application "Google Chrome"

   activate

   set currentTab to the active tab of the first window

   set URL of currentTab to theURL

end tell

on replace_spaces(theText)

   set AppleScript's text item delimiters to " "

   set theText to theText as text

   set theText to theText's text items as string

   set AppleScript's text item delimiters to "-"

   set theText to theText as text

   set AppleScript's text item delimiters to ""

   return theText

end replace_spaces

Upvotes: 0

Views: 298

Answers (1)

Ron Reuter
Ron Reuter

Reputation: 1347

There are several problems with ChatGPT's script (no surprises there!) The replace_spaces method was totally wrong. Other potential issues were not ensuring that Google Chrome was running and that it had at least one open window. Also, the format of the URL was not quite right to work with that site.

This works in my testing.

use AppleScript version "2.4"
use scripting additions

set theText to (the clipboard as text)

set theText to "hook up" -- for testing only, then comment this out

set theText to replace_spaces(theText)

set theURL to "https://www.dictionary.com/browse/" & theText

if application "Google Chrome" is not running then
    launch application "Google Chrome"
    delay 1
end if

tell application "Google Chrome"
    
    activate
    
    if (count of windows) is 0 then
        make new window
    end if
    
    set currentTab to the active tab of the first window
    
    set URL of currentTab to theURL
    
end tell

on replace_spaces(theText)
    
    set savedTIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to " "
    set theTextItems to theText's text items
    set AppleScript's text item delimiters to "-"
    set theText to theTextItems as text
    set AppleScript's text item delimiters to savedTIDs
    return theText
    
end replace_spaces

Upvotes: 1

Related Questions