// Source plain text
// If dispaly is true, special characters are formatted. For example, convert the space entered by the delimiter into an ampersand (\ r \ n) and convert it to <br>
// Tabs 4
Function htmlencode (source, display, tabs)
{
Function special (source)
{
VaR result = '';
For (VAR I = 0; I <source. length; I ++)
{
VaR c = source. charat (I );
If (C <''| C> '~ ')
{
C = ''+ C. charcodeat () + ';';
}
Result + = C;
}
Return result;
}
Function Format (source)
{
// Use only integer part of tabs, and default to 4
Tabs = (tabs> = 0 )? Math. Floor (tabs): 4;
// Split along line breaks
VaR lines = source. Split (/\ r \ n | \ r | \ n /);
// Expand tabs
For (VAR I = 0; I <lines. length; I ++)
{
VaR line = lines [I];
VaR newline = '';
For (VAR p = 0; P <line. length; P ++)
{
VaR c = line. charat (P );
If (C = '\ t ')
{
VaR spaces = tabs-(newline. Length % tabs );
For (var s = 0; S <spaces; s ++)
{
Newline + = '';
}
}
Else
{
Newline + = C;
}
}
// If a line starts or ends with a space, it evaporates in HTML
// Unless it's an nbsp.
Newline = newline. Replace (/(^) | ($)/g, '& nbsp ;');
Lines [I] = newline;
}
// Re-join lines
VaR result = lines. Join ('<br/> ');
// Break up contiguous blocks of spaces with non-breaking spaces
Result = result. Replace (// G, '& nbsp ;');
// Tada!
Return result;
}
VaR result = source;
// Ampersands (&)
Result = result. Replace (/\ &/g, '& amp ;');
// Less-thans (<)
Result = result. Replace (/\ </g, '& lt ;');
// Greater-thans (>)
Result = result. Replace (/\>/g, '& gt ;');
If (Display)
{
// Format for display
Result = format (result );
}
Else
{
// Replace quotes if it isn' t for display,
// Since it's probably going in an HTML attribute.
Result = result. Replace (New Regexp ('"', 'G'), '& quot ;');
}
// Special characters
Result = Special (result );
// Tada!
Return result;
}