double quotes in string from outside source

I am trying to setup a service using Applescript to select a bunch of text and run some grammar count measures on the selected text. The problem is the text will likely have single and double quotes. That means i can’t use any of the command line or Applescript tools because of the double quotes aren’t escaped. Without those tools, there no way to replace the double quotes.Trying to char the string to replace the quotes at a char level with something else wouldn’t work either for the same reason.

Anyone have any ideas?

If you’re using a service to collect the selection, everything that needs escaping will be escaped in the string passed to you.

Most important to know that there is no escaping/quoting of strings after they’re interpreted. The escaping in AppleScript of character is only for the user and not for the programming language itself. It allowed the developer to write strings embedded in the code instead of reading it from an device or file. The same applies for the command line utilities using a C string or the quotation in a bash string.

But of course when an string is send to another interpreter it needs to be escaped into the right format. For command line utilities there is the property quoted form so the string will be interpreted as a whole using a do shell script. It’s built-in AppleScript so we don’t have to do it ourself. Bash uses quite an unique string interpretation and therefore it’s better not do it yourself unless you are fully aware how bash strings works.

set theFile to POSIX path of (path to desktop folder as string) & "test.txt"
set theContents to read theFile

-- quote the string using the quoted form property
do shell script "/bin/echo -n " & quoted form of theContents & " | wc -c"

The script above will read the string into the variable theContents. When we use that string in an do shell script we use the quoted form property of the string instead and not the contents of the string. You can test the script above yourself and put any character in a file test.txt stored at your Desktop. The wc command will always return the length of the file.