在构建html时,在javascript中支持撇号的正确方法是什么? [英] What is the correct way to support apostrophes in javascript when building up html?

查看:115
本文介绍了在构建html时,在javascript中支持撇号的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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 issue is that i have a situation where there is an apostrophe in the name variable so it causes problems with this:

  value='" + name + "'

写这个的正确方法是什么,以避免与撇号有任何冲突?在C#中,我会做类似

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

  value=\"" + name + "\"

但这似乎不适用于javascript

but that doesn't seem to work in javascript

推荐答案

您要做的是清理您的输入。为此,您可以定义一个帮助器方法,用Unicode等效或HTML实体替换任何不安全的字符。这种东西不仅用于转义引号,还可以帮助防止像 XSS Attacks

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.

以下内容改编自使用jQuery转义HTML字符串的其他问题,请访问//stackoverflow.com/a/12034334\"> Tom Gruner的回答 。

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

var entityMap = {
    "&": "&amp;",
    "<": "&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>");



长期修复



如果你发现自己做了很多,然后可能是时候开始使用模板库,它可以自动执行此操作。我推荐并发现有用的一个模板库是 Google Closure模板。它是一个企业级模板库,默认情况下会清理HTML。

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.

有关Closure模板如何帮助保护您的更多信息,您可以查看页面他们有安全性

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

这篇关于在构建html时,在javascript中支持撇号的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆