Javascript obtains the real length of a string (two bytes are converted to two single bytes), truncates a fixed length substring.
Source: Internet
Author: User
<HTML>
<Head>
<Title> </title>
</Head>
<Body>
<Div id = 'jsdiv 'style = "border: 1px solid # CCC"> </div>
<SCRIPT type = "text/JavaScript">
// Obtain the real length of the string (two bytes are converted into two single bytes)
Function getstractuallen (schars)
{
Return schars. Replace (/[^/x00-/xFF]/g, "XX"). length;
}
// Truncate a fixed-length substring. ssource is the string. ilen is the length.
Function getinterceptedstr (ssource, ilen)
{
If (ssource. Replace (/[^/x00-/xFF]/g, "XX"). Length <= ilen)
{
Return ssource;
}
VaR STR = "";
VaR L = 0;
VaR schar;
For (VAR I = 0; schar = ssource. charat (I); I ++)
{
STR + = schar;
L + = (schar. Match (/[^/x00-/xFF]/)! = NULL? 2: 1 );
If (L> = ilen)
{
Break;
}
}
Return STR;
}
VaR str1 = "this is a string truncation function, this is a test! 2 ";
Alert (getstractuallen (str1 ));
Alert (getinterceptedstr (str1, 25 ));
</SCRIPT>
</Body>
</Html>
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