stringHandle.js 1.16 KB
/*
 * @Author: Targaryen
 * @Date: 2017-05-22 16:48:15
 * @Last Modified by: Targaryen
 * @Last Modified time: 2017-05-22 16:53:18
 */
var stringHandle = {

    /**
     * 汉字相当于两个字符的字符串长度计算
     * @param {*} str
     */
    chinese2: function(str) {
        var total = 0,
            charCode,
            i,
            len;

        for (i = 0, len = str.length; i < len; i++) {
            charCode = str.charCodeAt(i);
            if (charCode <= 0x007f) {
                total += 1;
            } else {
                total += 2;
            }
        }
        return total;
    },

    /**
     * 中文相当于两个字符情况下的字符串截取
     * @param {*} str
     * @param {*} n
     */
    sub_chinese2: function(str, n) {
        var r = /[\u4E00-\u9FA5]/g;
        var m = Math.floor(n / 2);
        var i;

        if (str.replace(r, 'mm').length <= n) {
            return str;
        }

        for (i = m; i < str.length; i++) {
            if (str.substr(0, i).replace(r, 'mm').length >= n) {
                return str.substr(0, i);
            }
        }
        return str;
    }
};

module.exports = stringHandle;