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

    /**
     * 汉字相当于两个字符的字符串长度计算
     * @param {*} str
     */
    chinese2(str) {
        let 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(str, n) {
        let r = /[\u4E00-\u9FA5]/g;

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

        let m = Math.floor(n / 2);

        for (let 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;