今天一个小弟问我的问题,在文本框中输入字符,如果超出指定长度,就把它截取,要求中文等于两个字符的长度,我找一下资料,把这个功能实现了,下面是JS代码:
<html>
<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script> <body>
<input type="text" name="username" />
</body>
<script type="text/ecmascript"> var GetLength = function (str) {
///<summary>获得字符串实际长度,中文2,英文1</summary>
///<param name="str">要获得长度的字符串</param>
var realLength = 0, len = str.length, charCode = -1;
for (var i = 0; i < len; i++) {
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128) realLength += 1;
else realLength += 2;
}
return realLength;
};
//js截取字符串,中英文都能用
//如果给定的字符串大于指定长度,截取指定长度返回,否者返回源字符串。
//字符串,长度 /**
* js截取字符串,中英文都能用
* @param str:需要截取的字符串
* @param len: 需要截取的长度
*/
function cutstr(str, len) {
var str_length = 0;
var str_len = 0;
str_cut = new String();
str_len = str.length;
for (var i = 0; i < str_len; i++) {
a = str.charAt(i);
str_length++;
if (escape(a).length > 4) {
//中文字符的长度经编码之后大于4
str_length++;
}
str_cut = str_cut.concat(a);
if (str_length >= len) {
str_cut = str_cut.concat("...");
return str_cut;
}
}
//如果给定字符串小于指定长度,则返回源字符串;
if (str_length < len) {
return str;
}
}
$(function () {
$("input[name=username]").bind('keyup', function () {
if (GetLength($(this).val()) > 10) {
$(this).val(cutstr($(this).val(), 10));
return;
}
});
});
</script>
</html>
效果如图:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAU8AAABNCAIAAACpEHEaAAAIgklEQVR4nO2cQUgjWRrHv+O71LFgqWOQBvGSQyB4aDIgiAziQcKChyBD5iC9SE6hnThtT9gWFhsP4l481EUXjKwMvelBBrLTQjA7vcbYLTrbLTFoKwabINSlLnV5e6iYVFIvnahRk37/H9+pfPXeV1C/enlfvZL+2PsvAoGQIejg/VsEAiFD0E8inj9vHjN1MVOOZzPPq/GsHD+KYvrH+og5Y1oQPzgjVo0pQcwI4+kPCISkQRwAIAewHQBZgO0AyAJsB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