【问题标题】:Better Way to write this to escape HTML content编写此代码以转义 HTML 内容的更好方法
【发布时间】:2012-02-28 09:31:44
【问题描述】:

我有富文本内容的字符串

例如这样的东西

<p>Hello</p>

<br/>

<p> Christian </p>

<pre> Don't Know what to do </pre>

现在我不希望脚本出现在上面的内容中,如果存在的话就放弃它

所以如果我的内容看起来像这样

<p>Hello</p>

<br/>

<p> Christian </p>
<script type="text/javascript"> alert("Hello")</script>
<pre> Don't Know what to do </pre>

需要替换为

<p>Hello</p>

<br/>

<p> Christian </p>
&lt;script type="text/javascript"&gt; alert("Hello")&lt;/script&gt;
<pre> Don't Know what to do </pre>

我目前已经为它开发了正则表达式

所以我的代码看起来像这样

if content.match(/<script(.+?)>/) {
  content = content.replace(content.match(/<script(.+?)>/)[0],content.match(/<script(.+?)>/)[0].replace("<","&lt;").replace(">","&gt;"))
}
if content.match(/<\script\s*>/)
 {
content = content.replace(content.match(/<\/script\s*>/)[0],content.match(/<\/script\s*>/)[0].replace("<","&lt;").replace(">","&gt;"))
}

所以结果内容将有脚本标签转义

谁能建议我更清洁的方法来实现这一目标?

【问题讨论】:

标签: javascript regex recursive-regex


【解决方案1】:

清洁工:

content = content.replace(/<(script[^>]*|\/script)>/g, '&lt;$1&gt;');

但是,这可能不是解决这个问题的方法。为什么JS字符串中会出现这些&lt;script&gt;标签?

【讨论】:

  • 谢谢@jensgram,我正在使用markitup富文本编辑器,我希望脚本标签被阻止我知道或不知道粘贴或写它们
【解决方案2】:

我认为你应该逃离那些角色服务器端。例如在 PHP 中你使用htmlentities

【讨论】:

  • 天啊,我真是太愚蠢了……写 addlashes() 哈哈。感谢您提供正确的解决方案。
【解决方案3】:

不是您要寻找的答案,但是如果禁用了 javascript 怎么办?您是否要让未转义的内容显示在页面上。 希望不会

转义必须使用服务器端脚本来完成,例如 PHPASP.NET 等。

在 PHP 中,htmlentities()[docs here] 就可以了

$escaped = htmlentities($content)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2017-08-19
    • 2020-01-29
    • 2010-12-08
    • 2012-05-08
    • 1970-01-01
    • 2011-11-19
    • 2013-04-07
    相关资源
    最近更新 更多