6

转义 html 很好 - 它会删除<'s 和>'s 等。

我遇到了一个问题,我在注释标签中输出文件名,例如。<!-- ${filename} -->

当然,如果你不逃跑,事情可能会很糟糕,所以它变成: <!-- <c:out value="${filename}"/> -->

问题是,如果文件的名称中有“--”,所有的 html 都会被搞砸,因为你不允许有<!-- -- -->.

标准的 html 转义不会转义这些破折号,我想知道是否有人熟悉一种简单/标准的转义方式。

4

5 回答 5

7

HTML 注释的定义

注释声明以 <! 开头,后跟零个或多个注释,然后是 >。注释以“--”开头和结尾,并且不包含任何“--”。

当然,评论的解析取决于浏览器。

这里没有什么让我印象深刻的解决方案,所以我建议你 str_replace 那些双破折号。

于 2008-11-26T05:24:53.673 回答
0

没有好的方法可以解决这个问题。您不能只是逃避它们,因为评论是以明文形式阅读的。您将不得不做一些事情,例如在连字符之间放置一个空格,或者对连字符使用某种代码(如[HYPHEN])。

于 2008-11-26T05:26:16.993 回答
0

没有通用的工作方法可以在 html 中转义这些字符,除非 - 字符是四的倍数,所以如果你这样做 - 它不会在 Firefox 中工作,但 ---- 会工作。所以这一切都取决于浏览器。例如,查看 Internet Explorer 8,这不是问题,那些字符被正确转义。Google 的 Chrome 也是如此……然而,即使是最新的浏览器(3.0.4),Firefox 也不能很好地处理这些字符的转义。

于 2008-11-26T05:36:49.733 回答
0

由于您不能直接显示 '--' 是很明显的,因此您可以对它们进行编码或使用 fn:escapeXml 或 fn:replace 标签进行适当的替换。 JSTL 文档

于 2008-11-26T05:40:48.680 回答
0

您不应该尝试 HTML 转义,注释的内容是不可转义的,可以使用裸露的 '>' 或 '&' 里面。

‘--’ is its own, unrelated problem and is not really fixable. If you don't need to recover the exact string, just do a replacement to get rid of them (eg. replace with ‘__’).

If you do need to get a string through completely unmolested to a JavaScript that will be reading the contents of the comment, use a string literal:

<!-- 'my-string' -->

which the script can then read using eval(commentnode.data). (Yes, a valid use for eval() at last!)

Then your escaping problem becomes how to put things in JS string literals, which is fairly easily solvable by escaping the ‘'’ and ‘-’ characters:

<!-- 'Bob\x27s\x2D\x2Dstring' -->

(You should probably also escape ‘&lt;’, ‘&amp;’ and ‘"’, in case you ever want to use the same escaping scheme to put a JS string literal inside a <​script> block or inline handler.)

于 2008-11-26T13:52:28.140 回答