6

I need to encode a string into Javascript text.

By googling I found the very useful function SourceCodeEscapers.javascriptEscaper which should be in Guava in the com.google.common.escape.CharEscaper package.

But it doesn't seem to be there in the actual Guava 13.0.1 release. (Also Dzone has a note about the new CharEscapers in Release 11, but I cannot find anything about it in the release notes.)

Has the CharEscaper-class moved? Was it never in Guava? Will it come in future releases?

Sonson123
  • 10,879
  • 12
  • 54
  • 72

2 Answers2

6

It's not in Guava yet, but it will be. As I understand it, the API's still being tweaked and refined before we release it and get locked into supporting backward compatibility.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

In Guava 20 there are a number of escapers but none that provides a method to escape for JavaScript. Apache Commons StringEscapeUtils provides such a method (including an "unescape" version) and from what I've tested seems to work reasonably well but it is curiously marked as deprecated. Perhaps too complex to deal with authoritatively ??

Just to be clear on the use case, I have used StringEscapeUtils#escapeEcmaScript to escape a Java string (JSON string actually) in a way that it could be placed verbatim, as a literal (inside '..') in generated JavaScript code and it worked well (as described here). Haven't tried the sibling unescape method though.

Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331
  • It is marked as deprecated because the class has moved to the library `org.apache.commons:commons-text`. It lives in the package [org.apache.commons.text](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html). – Daniel Beer Jan 27 '20 at 13:35