Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping javascript string in java

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.

like image 507
A_Elric Avatar asked Aug 29 '12 16:08

A_Elric


People also ask

How do I escape a string in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

Do I need to escape in JavaScript string?

The only characters you normally need to worry about in a javascript string are double-quote (if you're quoting the string with a double-quote), single-quote (if you're quoting the string with a single-quote), backslash, carriage-return (\r), or linefeed (\n).

How do you escape a string from a string?

In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal.

What is escape JavaScript?

The escape() function in JavaScript is used for encoding a string. It is deprecated in JavaScript 1.5.


3 Answers

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

like image 189
Denys Séguret Avatar answered Nov 01 '22 13:11

Denys Séguret


Looks like it was moved in Apache Commons Lang 3 to ESCAPE_ECMASCRIPT in StringEscapeUtils.

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

like image 36
Kirk Rasmussen Avatar answered Nov 01 '22 12:11

Kirk Rasmussen


It seems it moved yet again, now it is part of "commons-text" and is named:

StringEscapeUtils.escapeEcmaScript

But good it still exists.

like image 7
Tinus Tate Avatar answered Nov 01 '22 13:11

Tinus Tate