fc.util
Class HTMLUtil

java.lang.Object
  extended by fc.util.HTMLUtil

public final class HTMLUtil
extends Object


Constructor Summary
HTMLUtil()
           
 
Method Summary
static String entityToQuote(String str)
          Replaces embedded entities for single and double quotes, back to the correspoding single and double quote characters.
static void main(String[] args)
           
static String quoteToEntity(String str)
          Replaces all occurences of single and double quotes with corresponding HTML entities.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

HTMLUtil

public HTMLUtil()
Method Detail

quoteToEntity

public static String quoteToEntity(String str)
Replaces all occurences of single and double quotes with corresponding HTML entities. This is useful when setting attribute values containing those characters and maintaining state for characters typed by the user. For example,
<input type=text value='O'Reilly'>
O'Reilly could have been typed in by the user (and we are maintaining state so we have to show the value back to the user) or it could have been retrieved from the database. Either way, when the form is resubmitted, it would not be sent properly by the browser.

The embedded single quote in the value trips up the browser, because it prematurely ends the value. One would think that the following backslash-escape would work:

<input type=text value='O\'Reilly'>
Unfortunately, escaping like this does not work reliably in firefox, safari or IE.

Here is another example:

<input type=text value="foo"bar">
The following escape does not work either:
<input type=text value="foo\"bar">
To be safe, all embedded quotes must be encoded using character escapes: (single quote (') as &#39; ) and double quote (double (") as &#34; ). So
<input type=text value='O&#39;Reilly'>
This works fine and is submitted by the browser as O'Reilly

This method is critically useful. Learn it. Live it.


entityToQuote

public static String entityToQuote(String str)
Replaces embedded entities for single and double quotes, back to the correspoding single and double quote characters. This method is the converse of quoteToEntity(String)


main

public static void main(String[] args)