How do I escape quotes in HTML attribute values?


I’m building up a row to insert in a table using jQuery by creating a html string, i.e.

var row = "";
row += "<tr>";
row += "<td>Name</td>";
row += "<td><input value='""'/></td>";
row += "</tr>"; is a string returned from an ajax call which could contain any characters. If it contains a single quote, ', it will break the HTML by defining the end of the attribute value.

How can I ensure that the string is rendered correctly in the browser?


You just need to swap any ' characters with the equivalent HTML entity character code:'/g, "&#39;");

Alternatively, you could create the whole thing using jQuery’s DOM manipulation methods:

var row = $("<tr>").append("<td>Name</td><td></td>");
$("<input>", { value: }).appendTo(row.children("td:eq(1)"));

Answered By – Andy E

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.