Search code examples
delphidelphi-xe8

Unable to use apostrophes in a string


So I just spent an hour trying to get this to work. I'm doing some tests on TWebBrowser, so I could apply my findings in a project. I wanted to test different ways of loading content into it (URL, LoadFromStrings() and EvaluateJavaScript()). The problem is, I can't in anyway to pass a simple string into the last method without it being erroneously being entrapped in apostrophes.

procedure TForm1.FormCreate(Sender:TObject);
const S='<span style="color:red">ABC</span><span style="color:green">ABC</span><span style="color:blue">ABC</span>';
begin
WebBrowser1.LoadFromStrings('<html><body><div id="target">[x]</div></body></html>','');
WebBrowser1.EvaluateJavaScript('document.getElementById("target").insertAdjacentHTML('+
'"beforend",'#39+S+#39');');
end;

See the #39? Without them, the string gets sent with no apostrophes at all, so the resulting JavaScript script is invalid. If they remain, I get two apostrophes at each end of the string, still messing the script up. What is this?


Solution

  • My pshychic debugging tells me that you are looking at the string in the debugger. The single quote is the string delimiter. So it needs to be escaped. It is escaped by doubling it. So when the debugger shows a string like this:

    'a''b'
    

    that is actually three characters long, the middle character being a single quote.

    So

    Writeln('a''b');
    

    outputs

    a'b
    

    Or to use an example with your code, consider this complete program:

    {$APPTYPE CONSOLE}
    const
      S = '<span style="color:red">ABC</span>';
    begin
      Writeln(#39 + S + #39);
    end.
    

    This program outputs:

    '<span style="color:red">ABC</span>'
    

    And if you want to avoid using hard coded character codes you can use the escaped single quote like this:

      Writeln('''' + S + '''');