如何对html输出做编码转义,如何对字符串进行HTML编码/转义?有内置的吗?

h() is also useful for escaping quotes.

For example, I have a view that generates a link using a text field result[r].thtitle. The text could include single quotes. If I didn't escape result[r].thtitle in the confirm method, the Javascript would break:

<%= link_to_remote "#{result[r].thtitle}", :url=>{ :controller=>:resource,

:action =>:delete_resourced,

:id => result[r].id,

:th => thread,

:html =>{:title=> "<= Remove"},

:confirm => h("#{result[r].thtitle} will be removed"),

:method => :delete %>

<a href="#" οnclick="if (confirm('docs: add column &apos;dummy&apos; will be removed')) { new Ajax.Request('/resource/delete_resourced/837?owner=386&th=511', {asynchronous:true, evalScripts:true, method:'delete', parameters:'authenticity_token=' + encodeURIComponent('ou812')}); }; return false;" title="<= Remove">docs: add column 'dummy'

Note: the :html title declaration is magically escaped by Rails.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 是的,Node.js 有一个内置的库叫 `querystring`,它可以用来解析和格式化 URL 查询字符串。你可以用它来将 HTML 转义字符转换为普通字符串。 例如,你可以使用 `querystring.unescape()` 函数将 HTML 转义字符转换为普通字符串: ``` const querystring = require('querystring'); const htmlEscapedString = '%3Chtml%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E'; const unescapedString = querystring.unescape(htmlEscapedString); console.log(unescapedString); // '<html><body></body></html>' ``` 此外,还有许多第三方库,如 `he` 和 `html-entities`,也可以用来进行 HTML 转义。 ### 回答2: 是的,Node.js有许多用于查询HTML转义的库。其最常用的是`html-entities`库。这个库提供了一组实用的方法,可以用来转义HTML的特殊字符。使用该库,您可以很容易地将HTML转义成纯文本,以防止潜在的XSS攻击。 要使用`html-entities`库,您需要先安装该模块。在Node.js的命令行键入以下命令即可安装: ``` npm install html-entities ``` 安装完成后,您可以在您的Node.js应用程序引入并使用该库,以下是一个示例: ```javascript const Entities = require('html-entities').AllHtmlEntities; const entities = new Entities(); // 要转义HTML字符串 const htmlString = '<script>alert("XSS");</script>'; // 进行HTML转义 const escapedString = entities.encode(htmlString); console.log(escapedString); // 输出: '<script>alert("XSS");</script>' ``` 上述示例,我们首先导入`html-entities`库,然后创建了一个`Entities`对象。然后,我们定义了一个要转义HTML字符串,使用`encode`方法将其进行HTML转义,并将转义后的字符串打印到控制台。 通过使用这个库,您可以确保从外部来源接收到的HTML代码在展示时不会执行任何危险的脚本。这对于Web应用程序的安全性至关重要。 ### 回答3: 是的,Node.js有一些库可用于查询HTML转义。其最常用的库是"he"和"html-entities"。 "he"是一个用于HTML实体编码和解码的库。它可以将HTML的特殊字符如"<", ">", "&"等转义为对应的实体编码,也可以将实体编码转换回特殊字符。 "html-entities"也是一个常用的HTML实体转义库。除了提供HTML实体编码和解码功能外,它还提供了额外的功能,如指定字符集转换和对特定字符进行编码。 这些库都可以通过npm安装并在Node.js应用程序使用。您可以使用它们来处理需要转义或解码HTML实体的字符串,以确保在HTML显示正确的格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值