15

I need to make this into a string in 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.

.

.

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).

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.

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.

4

3 に答える 3

23

Apache commons have a methods just for this in StringEscapeUtils : the escapeJavaScript method.

于 2012-08-29T16:10:14.377 に答える
8

Apache CommonsLang3でStringEscapeUtilsのESCAPE_ECMASCRIPTに移動されたようです。

https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/src-html/org/apache/commons/lang3/StringEscapeUtils.html#line.74

于 2016-08-23T21:32:37.590 に答える
7

再び動いたようですが、今では「commons-text」の一部であり、次の名前が付けられています。

StringEscapeUtils.escapeEcmaScript

しかし、それはまだ存在しています。

于 2018-06-20T18:19:37.540 に答える