Search code examples
applescripturlencode

I need to URL-encode a string in AppleScript


My script searches a website for songs, but when there are spaces it doesn't search, you have to add underscores. I was wondering if there was a way to replace my spaces with underscores. Could you please use my current code below to show me how to do it?

set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
open location "http://www.mp3juices.com/search/" & search
end

Solution

  • Note: The solution no longer works as of Big Sur (macOS 11) - it sounds like a bug; do tell us if you have more information.

    Try the following:

    set search to text returned of (display dialog "Enter song you wish to find" default answer "" buttons {"Search", "Cancel"} default button 1)
      do shell script "open 'http://www.mp3juices.com/search/'" & quoted form of search
    end
    

    What you need is URL encoding (i.e., encoding of a string for safe inclusion in a URL), which involves more than just replacing spaces. The open command-line utility, thankfully, performs this encoding for you, so you can just pass it the string directly; you need do shell script to invoke open, and quoted form of ensures that the string is passed through unmodified (to be URI-encoded by open later).

    As you'll see, the kind of URL encoding open performs replaces spaces with %20, not underscores, but that should still work.