zoukankan      html  css  js  c++  java
  • 超过长度的字符截取指定长度,超出部分以...显示

    $(function () {
            subString('abcdef你好!Hello World', 6);
        })
        //超过长度的字符截取指定长度,超出部分以...显示,中文字符是两个字符长度
        function subString(str, len) {
            var newLength = 0;
            var newStr = "";
            var chineseRegex = /[^x00-xff]/g;//中文正则表达式
            var singleChar = "";
            var strLength = str.replace(chineseRegex, "**").length;
            if (strLength > len) {
                for (var i = 0; i < strLength; i++) {
                    singleChar = str.charAt(i).toString();
                    if (singleChar.match(chineseRegex) != null) {
                        newLength += 2;
                    }
                    else {
                        newLength++;
                    }
                    if (newLength > len) {
                        break;
                    }
                    newStr += singleChar;
                }
    
                if (strLength > len) {
                    newStr += "...";
                }
            } else {
                newStr = str;
            }
            return newStr;
        }
  • 相关阅读:
    隔离级别
    cookie
    session
    正则表达式
    hello2源代码解析
    servlet_filter简介
    web.xml
    Annotations
    Java design patterna
    CDI Features
  • 原文地址:https://www.cnblogs.com/Loners/p/12502200.html
Copyright © 2011-2022 走看看