Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape quote when using StringBuilder

Tags:

java

html

I'm using StringBuidler in Java to build a HTML page.

I want to know how to escape all quotes (") without placing a "\" every time? For example, every time when I append a string like this :

StringBuilder a ;
a.append(<div id = \"Name\" ...>)

I want to write directly :

a.append(<div id = "Name" ..>

Thanks.

like image 888
hawarden_ Avatar asked Sep 18 '26 16:09

hawarden_


2 Answers

Short answer: There is no way around this in Java

Long answer: Java does not have multiple ways to enclose Strings. You always do it with double quotes, so if you want to have double quotes in your String you have to escape them.

But if they really annoy you you can apply some trickery:

  1. put your Strings in a text file and read them from there.

  2. use a different character instead of the quote character and use replace to put in the proper quotes. Of course your replacement character must not appear anywhere else in the string.

  3. Write the code in question in a different programming language like Groovy, which has different ways to delimit Strings.

Since you seem to generate HTML: use a proper templating engine, which really is option 1 on steroids.

like image 135
Jens Schauder Avatar answered Sep 20 '26 04:09

Jens Schauder


When building a HTML template, the easiest solution is to use a text file.

You can do this as

  • a simple text file where you replace() tags with code you want to alter
  • use a properties file for the sections of text to inline.
  • use a library which has a fluent API for generating HTML
  • use velocity to perform the substitution for you.
  • use one of the other many web page formats like JSP.

However, there is no way to avoid escaping " in Java code. The only alternative is you use another character like (Alt-Graphic-B) which you replace at the end.

like image 41
Peter Lawrey Avatar answered Sep 20 '26 06:09

Peter Lawrey