Just like other general purpose development tools Process Automation cannot predetermine the purpose of your string. That is why all of these languages/APIs have functionality, not all of them the same, to indicate a string is a "static" string and a way to escape special characters.
Process Automation 4.3
The need to encode the string or not needs to be explicitly defined and can only be determined with an full understanding of the activities being programmed into a PAM Process. This is not PAM specific functionality, this is standardized technology which is being leveraged by Process Automation.
This is important because we simply can not document and convey all possible functionality of all possible function calls that can be leveraged from within PAM and expect a certain level of understanding of the code language(s) being used.
As an example, you could specifically tell PAM to replace special characters explicitly:
Process.outputString = Process.inputString.replace(/&/g, "&");
Process.outputString = Process.inputString.replace(/</g, "<");
Process.outputString = Process.inputString.replace (/>/g, ">");
Process.outputString = Process.inputString.replace (/"/g, """);
Process.outputString = Process.inputString.replace (/'/g, "'");
This can be used in place of the multiple .replace statements, where instead of telling PAM to encode each specific character, possibly requiring many lines of replace statements, you are telling PAM to encode the entire string with a single line.
Please see http://www.w3schools.com/jsref/jsref_encodeuri.asp for more information.
Another potential workaround to try is the replacement of the apostrophe by a %, which would represent a wildcard in the query.
You should also be aware that if a text value is passed into a Run Script operator that contains carriage returns, those carriage returns can cause the script to fail or return incorrect results.