title: How to escape MathML String in Android for Javascript in WebView
body: <p>I am trying to display MathML in a WebView using MathJax.</p>
  
  <p>When displaying my own MathML this works well:</p>
  
  <pre><code>        w.evaluateJavascript("javascript:document.getElementById('math').innerHTML='"
                  + "New &lt;math xmlns=\"http://www.w3.org/1998/Math/MathML\"&gt;"
                  + "&lt;mi&gt;d&lt;/mi&gt;&lt;mo&gt;&amp;#x2260;&lt;/mo&gt;&lt;mn&gt;13&lt;/mn&gt;"
                  + "&lt;/math&gt;'",
                  null);
          w.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
  </code></pre>
  
  <p>However, when I try to display MathML which I get from a widget, the following does not work:</p>
  
  <pre><code>        mlOutput = mlOutput.replaceAll("(\\r|\\n)", ""); //some random trial and error
          mlOutput = mlOutput.replaceAll("'", "\\'");
          mlOutput = mlOutput.replaceAll("\'", "\\\'");
          mlOutput = mlOutput.replaceAll("'", "\\\'");
  
          w.evaluateJavascript("javascript:document.getElementById('math').innerHTML='"
                          + mlOutput+ "'",
                  null);
          w.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
  </code></pre>
  
  <p>mlOutput is a String which is printed to Logcat like this (before my string replacing):</p>
  
  <pre><code>&lt;math xmlns='http://www.w3.org/1998/Math/MathML'&gt;
  &lt;mfrac&gt;
  &lt;mrow&gt;
  &lt;mn&gt; 2 &lt;/mn&gt;
  &lt;/mrow&gt;
  &lt;mrow&gt;
  &lt;mn&gt; 3 &lt;/mn&gt;
  &lt;/mrow&gt;
  &lt;/mfrac&gt;
  &lt;/math&gt;
  </code></pre>
  
  <p>Also I get the following Info from chromium:</p>
  
  <pre><code>I/chromium﹕ [INFO:CONSOLE(1)] "Uncaught SyntaxError: Unexpected identifier", source:  (1)
  </code></pre>
  
  <p>Any help on how to appropriately escape the mlOutput MathML-String so that I can use it within Javascript would be highly appreciated!</p>
  
  <p>So far the best I could find was something about the Apache StringEscapeUtils.escapeJavaScript function. <strike>But as far as I know this can not be used within Android?</strike> I just imported the 500KB .jar library but this was not the solution.</p>
  
  <p><strong>Edit:</strong>
  the solution was some method from this MathJax sample implementation app <a href="https://github.com/leathrum/android-apps/tree/master/MathJaxApp" rel="nofollow">https://github.com/leathrum/android-apps/tree/master/MathJaxApp</a></p>
  
  <pre><code>mlOutput = doubleEscape(mlOutput);
  
  private String doubleEscape(String s) {
  String t="";
  for (int i=0; i &lt; s.length(); i++) {
    if (s.charAt(i) == '\'') t += '\\';
    if (s.charAt(i) != '\n') t += s.charAt(i);
    if (s.charAt(i) == '\\') t += "\\";
  }
  return t;
  }
  </code></pre>