Reputation: 2160
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
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
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
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:
put your Strings in a text file and read them from there.
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.
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
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
Reputation: 533492
When building a HTML template, the easiest solution is to use a text file.
You can do this as
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