AppleScript to massage URLs

I want to have a Services menu item that takes the selected text (a URL) and escapes the percent character and the # character:

  1. Replace % with \%
  2. Replace # with \string#

I copied and edited an exisiting script that does similar text manipulation. This seems to work fine except when the URL contains a &.

I think this has something to do with needing to use quoted form of string, but I can't quite determine the correct place to specify that.

Sample Input:

http://books.google.com?xxx&xxx%22+xxx#v=onepage&q=%22Search%20String&f=false

Required Output

http://books.google.com?xxx&xxx\%22+xxx\string#v=onepage&q=\%22Search\%20String&f=false

Code:

on run {input, parameters}
set sanatizedURLString to ¬
    (do shell script ("echo " & input & "  | sed 's/%/\\\\%/g' | sed 's/#/\\\\string#/g' ;"))
return sanatizedURLString
end run

This is how I'd code it:

on run {input, parameters}
    set aURL to input as string
    set sanatizedURL to ¬
        do shell script "sed -e 's:%:\\\\%:g' -e 's:#:\\\\string#:g' <<< " & aURL's quoted form 
    return sanatizedURL
end run

      Hint: Mouse over and horizontal scroll to see full code.


Notes:

input is a list e.g.:

{"http://books.google.com?xxx&xxx%22+xxx#v=onepage&q=%22Search%20String&f=false"}

set aURL to input as string makes it:

http://books.google.com?xxx&xxx%22+xxx#v=onepage&q=%22Search%20String&f=false

In the do shell script command sed only needs to be called once, not twice as in the original code. sed can take multiple commands by using the -e option, thus no need in this case to pipe the output of one sed command to another sed command.

It is not necessary to echo something to sed as it can process a file or a here string, thus the use of <<< in the do shell script command, followed by & aURL's quoted form which is e.g.:

'http://books.google.com?xxx&xxx%22+xxx#v=onepage&q=%22Search%20String&f=false'

By quoting the value of aURL it keeps the shell from processing any shell special characters in the string.

Thus, when run, the do shell script command looks like e.g.:

do shell script "sed -e 's:%:\\\\%:g' -e 's:#:\\\\string#:g' <<< 'http://books.google.com?xxx&xxx%22+xxx#v=onepage&q=%22Search%20String&f=false'"

      Hint: Mouse over and horizontal scroll to see full code.

The use of : vs. / in the sed command is a personal preference in this case as it makes the command easier to read when having to make multiple escapes.

The use of echo in the original code flattens the list to a string, however I prefer to not use that method in order to make the do shell script command less complicated.