<script type="text/javascript">
function substr(str, len) {
if (!str || !len) {
return '';
}
var a = 0;
var i = 0; //循环计数
var temp = ''; //临时字串
for (i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 255) {
a += 2; //按照预期计数增加2
} else {
a++;
}
if (a > len) { //如果增加计数后长度大于限定长度,就直接返回临时字符串
return temp;
}
temp += str.charAt(i); //将当前内容加到临时字符串
}
return str; //如果全部是单字节字符,就直接返回源字符串
}
var str = "呵呵he哈哈嘿嘿and";
document.write("字符串:<font color='red'>" + str + "</font><br /><br />");
document.write("javascript 默认截取10个字节的返回值:<br />");
document.write("<font color='red'>" + str.substr(0, 10) + "</font><br /><br />");
document.write("用本文介绍的方法截取10个字节的返回值:<br />");
document.write("<font color='red'>" + substr(str, 10) + "</font><br /><br />");
document.write("截取9个字节的返回值:<br />");
document.write("<font color='red'>" + substr(str, 9) + "</font><br /><br />");
</script>