public static String escapeHTML ( String string ) { if ( string == null ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; boolean lastCharacterWasSpace = false ; char [ ] chars = string . toCharArray ( ) ; for ( char c : chars ) { if ( c == ' ' ) { if ( lastCharacterWasSpace ) { lastCharacterWasSpace = false ; sb . append ( "&nbsp;" ) ; } else { lastCharacterWasSpace = true ; sb . append ( " " ) ; } } else { lastCharacterWasSpace = false ; switch ( c ) { case ' ' : sb . append ( "&lt;" ) ; break ; case ' ' : sb . append ( "&gt;" ) ; break ; case ' ' : sb . append ( "&amp;" ) ; break ; case ' ' : sb . append ( "&quot;" ) ; break ; default : sb . append ( c ) ; break ; } } } return sb . toString ( ) ; }
Escapes HTML Special characters present in the string .