【问题标题】:Remove every html tag with JsHtmlSanitizer使用 JsHtmlSanitizer 删除每个 html 标记
【发布时间】:2012-12-28 18:56:43
【问题描述】:

我终于得到了JsHtmlSanitizer 作为一个独立的客户端脚本工作。 现在我想从字符串中删除所有 HTML 标记,而不仅仅是脚本标记和链接。 这个例子

html_sanitize('<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"><\/script>');

返回 "hello" 但我想删除所有标签。

【问题讨论】:

  • 那个时候,为什么不直接把它当作一个XML文档,获取innerText呢?
  • 我想在我目前正在处理的程序中使用 bb-code 实现实时预览。所以首先我想删除所有 HTML-Tags,然后将 BB-Code 转换为 HTML
  • 那么为什么不把它当作一个 XML 文档来获取 innerText 呢?
  • 对不起,我不明白你的意思
  • @JohnDoe:看看jsfiddle.net/tarabyte/UeVgA/3。您可以将输入字符串转换为文档。并遍历它以获取文本节点或您喜欢的任何内容。

标签: javascript


【解决方案1】:

为什么不使用正则表达式在清理后删除所有 HTML 标签?

var input = '<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"></script>';
var output = null;
output = html_sanitize(input);
output = output.replace(/<[^>]+>/g, '');

这应该会在清理后去除您输入的 all html 标记字符串。

如果您只想进行基本的清理(删除脚本和样式标签及其内容和所有 html 标签),您可以在正则表达式中实现整个事情。我在下面演示了一个示例。

var input = '<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"></script>';
input += '<script> if (1 < 2) { alert("This script should be removed!"); } </script><style type="text/css">.cssSelectorShouldBeRemoved > .includingThis { background-color: #FF0000; } </style>';

var output = null;
output = input.replace(/(?:<(?:script|style)[^>]*>[\s\S]+?<\/(?:script|style)[^>]*>)|<[^>]+>/ig, '');

【讨论】:

【解决方案2】:

使用下面的这个 javascript 函数从 html_sanitize() 获得的字符串中删除所有 html 标记。

var output = html_sanitize('<b>hello</b><img src="http://google.com"><a href="javascript:alert(0)"><script src="http://www.google.com"><\/script>');

output = output.replace(/(<.*?>)/ig,"");

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-13
    • 2015-08-09
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2011-05-13
    相关资源
    最近更新 更多