-1

I need to initialize complex javascript code as an string. But that javascript code contains semicolon and " mark. I know I can escape " mark using \". But I don't know how to escape semicolon.

<script type="text/javascript"><!--
google_ad_client = "8888888888888";
/* Error Page Ads */
google_ad_slot = "8888888";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

I need to initialize above code as,

String complexString = "Above code here";

I can't concatenate slices of code, because that way ; will be removed. Right?

This is for Servlet. I may be foolish, but pardon me.

Erick Robertson
  • 30,990
  • 12
  • 68
  • 98
Isuru Madusanka
  • 1,387
  • 4
  • 18
  • 27

4 Answers4

4

As long as the ; is inside your double quotes you shouldn't need to escape it.

Baz
  • 35,635
  • 11
  • 69
  • 91
Jordan Denison
  • 2,539
  • 13
  • 14
3

Semicolons are not special characters. There's no need of escaping them when they're in a String. You can always test a string's behavior by using the little old System.out.println() method.

Fritz
  • 9,827
  • 4
  • 29
  • 49
3

You don't need to escape your ; when they are inside " or ', as they are literals and are perfectly safe.

Zach Jensz
  • 2,608
  • 3
  • 8
  • 23
Praveen Kumar Purushothaman
  • 160,666
  • 24
  • 190
  • 242
1

I think what you really want to do is escape the quote characters in your javascript not your semicolon characters.

So ultimately you would want

String complexString = "<script type=\"text/javascript\"><!--
google_ad_client = \"8888888888888\";
/* Error Page Ads */
google_ad_slot = \"8888888\";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>  
<script type=\"text/javascript\"
src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\">  
</script>"
Matthew Kirkley
  • 3,944
  • 4
  • 29
  • 33
  • [related](http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write) – jbabey Oct 08 '12 at 17:40