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

梦想的初衷 提交于 2019-12-05 06:00:48
Kyle Falconer

What you're looking to do is sanitize your input. To do this, you might define a helper method which replaces any unsafe characters with either the Unicode equivalent or the HTML entity. Not only is this sort of thing used for escaping quotes, but it can also help prevent things like XSS Attacks.

Short-term fix

The following is adapted from Tom Gruner's answer from this other question on Escaping HTML strings with jQuery.

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

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

And then to use this, you would do something like the following:

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>");

Long-term fix

If you find yourself doing this a lot, then it may be time to start using a template library which can do this automatically. One template library I recommend and find useful is the Google Closure Templates. It is an enterprise-grade template library which will (by default) sanitize your HTML.

For more information on how Closure Templates help protect you, you can check out the page they have on security.

You can quote characters:

var apostophe = '\''

or use HTML entities if intended to be used in an HTML document:

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

or use unicode:

var apostrophe = '\u0027';

So you can do:

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

Mapping of characters to one of the above (entity or Unicode value) is fairly simple using replace with a regular expression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!