hawarden_
hawarden_

Reputation: 2160

Escape quote when using StringBuilder

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.

Upvotes: 3

Views: 7063

Answers (5)

Kayaman
Kayaman

Reputation: 73528

You can't, which is only one of the reasons it's a bad idea to fill a StringBuilder with HTML code by hand.

Upvotes: 1

iandioch
iandioch

Reputation: 128

There's no proper way to do it, but you might be able to put a rarely used substitute character (a tilde or something) in your String and then call .replace() on it.

Ideally, you should be loading the data from a file if you want the raw string.

Upvotes: 0

Jens Schauder
Jens Schauder

Reputation: 81862

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.

Upvotes: 8

Karim BENHDECH
Karim BENHDECH

Reputation: 381

It exists in other language than Java, but with Java is not possible.

With coffescript, you can, for example :

 html = """
         <div id="Name" > ... </div>
        """ 

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

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.

Upvotes: 3

Related Questions