
趁我写例子这点时间有两个人回答了 呵呵
刚才试验过了 看下例子吧
JS 方法:
代码如下:
// 得到字符串的真实长度(双字节换算为两个单字节)
function getStrActualLen(sChars)
{
//sChars.replace(/[^\x00-\xff]/g,"xx").length/1024+"字节";
//Math.round(sChars.replace(/[^\x00-\xff]/g,"xx").length/1024);这个貌似不好使
return alert(formatNum(sChars.replace(/[^\x00-\xff]/g,"xx").length/1024,4));
}
//格式化小数,并四舍五入。如:formatNum(100.12345678,4)
function formatNum(Num1,Num2){
if(isNaN(Num1)||isNaN(Num2)){
return(0);
}else{
Num1=Num1.toString();
Num2=parseInt(Num2);
if(Num1.indexOf('.')==-1){
return(Num1);
}else{
var b=Num1.substring(0,Num1.indexOf('.')+Num2+1);
var c=Num1.substring(Num1.indexOf('.')+Num2+1,Num1.indexOf('.')+Num2+2);
if(c==""){
return(b);
}else{
if(parseInt(c)<5){
return(b);
}else{
return((Math.round(parseFloat(b)*Math.pow(10,Num2))+Math.round(parseFloat(Math.pow(0.1,Num2).toString().substring(0,Math.pow(0.1,Num2).toString().indexOf('.')+Num2+1))*Math.pow(10,Num2)))/Math.pow(10,Num2));
}
}
}
}
}
Jquery方法:
代码如下:
function getStrActualLen(){
var count=$("#sChars").val().length/1024;
return Math.round(count*Math.pow(10,4));
}
jquery 截取字符串长度
jquery 可以用text()方法来取得字符串,再用length 判断长度,然后用substring()方法格式化截断后加'...'省略号。
代码如下:
cookie script>
jQuery.fn.limit=function(){
var self = $('div[limit]');
self.each(function(){
var objString = $(this).text();
var objLength = $(this).text().length;
var num = $(this).attr('limit');
if(objLength > num){
$(this).attr('title',objString);
objString = $(this).text(objString.substring(0,num) + '...');
}
})
}
$(function(){
$(document.body).limit();
})
script>
请按F5刷新页面。。
字符串字符串字符串字符串字符串字符串字符串字符串字符串
字符串字符串字符串字符串字符串字符串字符串
字符串字符串字符串字符串字符串
字符串字符串字符串字符串字符串字符串字符串字符串
字符串字符串字符串字符串字符串字符串字符串