javascript 在java中转义javascript字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12182121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping javascript string in java
提问by A_Elric
I need to make this into a string in java:
我需要在java中把它变成一个字符串:
<script type="text/javascript">document.write("<img src=\"UpArrow.png\" /> \"); </script>
Can someone help? I keep trying and it ends up like this...
有人可以帮忙吗?我一直在努力,结果是这样......
return "<script type=\"text/javascript\">document.write(\"<img src=\"UpArrow.png\" /> \"); </script>";
Which doesn't work because I need to double escape the quotes before and after UpArrow.png. since it needs to be escaped in javascript and not in java.
这不起作用,因为我需要在 UpArrow.png 之前和之后双重转义引号。因为它需要在javascript中而不是在java中转义。
.
.
.
.
2019 Update:If you are looking at this, god help your soul. This is awful code and if you're trying to do things this way you're doing it wrong (As others suggested to me).
2019 更新:如果你正在看这个,上帝保佑你的灵魂。这是一段糟糕的代码,如果你试图以这种方式做事,那你就做错了(正如其他人向我建议的那样)。
The correct way to do this would be jquery or one of the zillion DOM-modifying frameworks that exist now and popping stuff into / out of the scope of the DOM.
执行此操作的正确方法是 jquery 或现在存在的无数 DOM 修改框架之一,并将内容弹出/弹出 DOM 的范围。
If you are doing this, you should not look at the code above or the solutions below, but should instead go learn more, as this is a path to make spaghetti code.
如果你这样做,你不应该看上面的代码或下面的解决方案,而应该去了解更多,因为这是制作意大利面条代码的途径。
回答by Denys Séguret
Apache commons have a methods just for this in StringEscapeUtils: the escapeJavaScript
method.
Apache commons 在StringEscapeUtils 中有一个专门用于此的escapeJavaScript
方法:方法。
回答by Kirk Rasmussen
Looks like it was moved in Apache Commons Lang 3 to ESCAPE_ECMASCRIPT in StringEscapeUtils.
看起来它在 Apache Commons Lang 3 中被移动到 StringEscapeUtils 中的 ESCAPE_ECMASCRIPT。
回答by Tinus Tate
It seems it moved yet again, now it is part of "commons-text" and is named:
似乎它又移动了,现在它是“commons-text”的一部分并被命名为:
StringEscapeUtils.escapeEcmaScript
But good it still exists.
但好在它仍然存在。