Javascript implements encoding for text encode

Source: Internet
Author: User

// 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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.