Search code examples
javascripthtmlescapingspecial-charactersdynamic-html

Escape special characters when building html code using javascript


Hi I would like to build html code dynamically using javascript. The problem is it gives me an syntax error when I try to specify css class for the table using . I think I need to escape the special characters = and "" here. And I tried something like this but it give an error of illegal syntax as well.

for (var i=0; i<array.length; i++)
{
    htmlstr = htmlstr+"<table class"+%3D+%22+"test"+%22+"><tr><th>A</th><td>"+array[i].a+"</td></tr><tr><th>B</th><td>"+array[i].b+"</td></tr><tr><th>C</th><td>"+array[i].c+"</td></tr></table>";
}

Does anyone know what is the correct syntax to do this?

Thanks in advance!


Solution

  • htmlstr=htmlstr+'<table class="test"><tr><th>A</th><td>'
                   +array[i].a+'</td></tr><tr><th>B</th><td>'
                   +array[i].b+'</td></tr><tr><th>C</th><td>'
                   +array[i].c+'</td></tr></table>';
    

    For example, if you want to encapsulate <input type="button" onClick="alert('Hello, World!');"></input> in a JavaScript string, you can't do it in one run, because the code contains both double " and single ' quotes. You should do something like this:

    var htmlCode='<input type="button" onClick="alert('+"'Hello, World!'"+');"></input>';
    

    You may use both single or double quotes to define a string variable in javascript:

    var str0='Hello, World!';
    var str1="Hello, World!";
    

    They are absolutely equal.