/*求出字节长度*/
String.prototype.byteLen = function(len) { if (!this) { return ''; } var a = 0, b = 0, i = 0, temp = ''; for (i = 0; i < this.length; i++) { a += this.charCodeAt(i) > 255 ? 2 : 1; if (len) { if (a > len && b > len - 1) { return temp + ".."; } if (this.charCodeAt(i) > 32) { temp += this.charAt(i); b += this.charCodeAt(i) > 255 ? 2 : 1; } } } return len ? this : a; }
document.write( '\n 个性的 测试数据 2010-11-12 15:00:54'.byteLen(30));
alert('\n 个性的 测试数据 2010-11-12 15:00:54'.byteLen());
js 求字符串 字节长度 截取字符串 终极解决方法!
/// <summary>
/// 字符串字节长度截取
/// </summary>
/// <param name="str"></param>
/// <param name="num"></param>
/// <returns></returns>
public static string SubBytestring(this string str, int num)
{
string strNum = str.Trim();
if (Encoding.Default.GetBytes(strNum.Trim()).Length <= num)
{
return strNum;
}
byte[] bytes2 = Encoding.Default.GetBytes(str.Substring(0, num));
string strNum1 = Encoding.Default.GetString(bytes2, 0, num);
int len = strNum1.Length;
if (str.Substring(0, len) != strNum1)
{
return Encoding.Default.GetString(bytes2, 0, num - 1);
}
return strNum1;
}