What is the correct way to support apostrophes in javascript when creating html?

I have the following code:

var name = "Joe O'Neal";

var row= [];
row.push(
  "<td><input type='hidden' name='milestones[" + id + "].Name' 
   value='" + name + "' class='currentRowName'  />
    <span class='currentRowNameText'>" + name + "</span></td>")

but the problem is that I have a situation where there is an apostrophe in the variable name, so it causes problems with this:

  value='" + name + "'

What is the correct way to write this to avoid conflicts with apostrophes? In C #, I would do something like

  value=\"" + name + "\"

but this does not work in javascript

+4
source share
2 answers

, , . , Unicode HTML. , , XSS Attacks.

Tom Gruner HTML jQuery.

var entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
};

function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
        return entityMap[s];
    });
}

, , - :

var name = "Joe O'Neal";
var safe_name = escapeHtml(name);

var row= [];
row.push(
    "<td><input type='hidden' name='milestones[" + id + "].Name' 
    value='" + safe_name + "' class='currentRowName'  />
    <span class='currentRowNameText'>" + safe_name + "</span></td>");

, , , , , . , , - Google Closure Templates. , ( ) HTML.

, Closure Templates , , security.

+4

:

var apostophe = '\''

HTML, HTML:

var apostrophe = '&apos;';
var apostrophe = '&#39;';

unicode:

var apostrophe = '\u0027';

, :

var name = 'O\u0027Neal';
el.innerHTML = '<input value="' + name + '">';

( Unicode) , .

+2

Source: https://habr.com/ru/post/1544079/


All Articles