Javascript 中英文字符串截取

 1 /**
 2   * 中英文字符串截取
 3   * @param str  要截取的字符串
 4   * @param len  要截取的长度
 5   * @param hasDot 是否在字符串末尾增加'...'
 6   * @returns {string}
 7   *
 8   */
 9           
10 function mySubString (str, len, hasDot){
11         var newLength = 0;
12         var newStr = "";
13         var chineseRegex = /[^\x00-\xff]/g;
14         var singleChar = "";
15         var strLength = str.replace(chineseRegex,"**").length;
16         for(var i = 0;i < strLength;i++)     {
17           singleChar = str.charAt(i).toString();
18           if(singleChar.match(chineseRegex) != null) {
19             newLength += 2;
20           }else {
21             newLength++;
22           }
23           if(newLength > len) {
24             break;
25           }
26           newStr += singleChar;
27         }
28         if(hasDot && strLength > len) {
29           newStr += "...";
30         }
31         return newStr;
32     }

 

举个例子,假如需要最多保留24个字符(中文算两个,英文算一个)

 

$('#inupt').on('keyup',function(){
    var newValue = $(this).val();
    var textLength = 0;
    var subStr;

    for (var i = 0; i < newValue.length; i++) {
      if (newValue.charAt(i).match(/[\u0391-\uFFE5]/)) {
        textLength += 2;
      } else {
        textLength++;
      }
    };

    subStr = mySubString(newValue,24);
    $(this).val(subStr);
$('#strLengh').text(
textLength);
})

 

posted @ 2015-09-17 12:10  蜉蝣生物  阅读(718)  评论(0编辑  收藏  举报