public static String escapeAttribute ( String string ) { if ( string == null || string . length ( ) == 0 ) { return string ; } StringBuilder resultBuffer = null ; for ( int i = 0 , length = string . length ( ) ; i < length ; i ++ ) { String entity = null ; char ch = string . charAt ( i ) ; switch ( ch ) { case ' ' : entity = "&quot;" ; break ; case ' ' : entity = "&amp;" ; break ; default : break ; } if ( entity != null ) { if ( resultBuffer == null ) { resultBuffer = new StringBuilder ( string ) ; resultBuffer . setLength ( i ) ; } resultBuffer . append ( entity ) ; } else if ( resultBuffer != null ) { resultBuffer . append ( ch ) ; } } return ( resultBuffer != null ) ? resultBuffer . toString ( ) : string ; }
Escape a string for use as an HTML attribute by replacing all double quotes and & .