How do I escape quotes in HTML attribute values?

Issue

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='"+data.name+"'/></td>";
row += "</tr>";

data.name 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?

Solution

You just need to swap any ' characters with the equivalent HTML entity character code:

data.name.replace(/'/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: data.name }).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.