Search code examples
javascriptstringreplacequotation-marks

Replace quotation marks with \"


I am working with a html-page with some javascript on it. What I'm trying to do is to show a message and a button after pressing submit-button. On pressing this new button the document state should go to its previous state. My attempt:

function Submin()
{
  var str=document.Inputs.innerHTML;
  newstr = str.replace("\"", "\\\"");
  document.Inputs.innerHTML="<p style=\"text-align:center\">The data has been successfully submitted <br /><input type=\"button\" value=\"Back\" onclick=\"document.Inputs.innerHTML=\\\"" + newstr + "\\\" \/></p>";
}

I am totally confused by escaping and double escaping things. But in my opinion it should work somehow like this. Can sombody help me on this solution?


Solution

  • First, you can use single quotes inside your double quoted string. Second, don't use inline event handlers here. Your best bet is to use a real event handler:

    function Submin() {
        var str=document.Inputs.innerHTML;
        document.Inputs.innerHTML="<p style='text-align:center'>The data has been successfully submitted <br /><input type='button' value='Back' ></p>";
        document.Inputs.getElementsByTagName("input")[0].onclick = function() {
            document.Inputs.innerHTML = newstr;
        };
    }