Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tools: getLimitString 前端截取字符串 #69

Open
mishe opened this issue Dec 22, 2015 · 0 comments
Open

tools: getLimitString 前端截取字符串 #69

mishe opened this issue Dec 22, 2015 · 0 comments

Comments

@mishe
Copy link
Owner

mishe commented Dec 22, 2015

前端截取字符串

出于移动端的手机界面的限制,每屏显示的内容有限,需要截断内容的展示,以便可以显示更多的列表内容,另外后端API出于各端的数据统一,只负责数据的完整性,那么这个任务就需要前端来做;

截取字符的思路和获取字符串长度的思路一致,先来看下识别字符串长度的函数:

charLen: function (string) {
        if (!string) return 0;
        return string.replace(/[^\x00-\xff]/g, '00').length;
    },

由源码可以看出,通过识别非ascii码的字符都算2个字符长度;

那么截止字符串的长度时,我们也可以通过这个来做处理,来看源码:

 getLimitString: function (str, limit) {
        var pos = 0;
        if (!limit || $.charLen(str) <= limit) return str;
        for (var i = 0; i < str.length; i++) {
            pos += str.charCodeAt(i) > 255 ? 2 : 1;
            if (limit <= pos) {
                return str.substr(0, i + 1)+'...';
                break;
            }
        }
    }

首先,判断字符串是否为空,或者长度比截取的长度还小,这返回原字符串

然后通过循环来计算截取的位置

最后通过substr来截取字符串并增加'...'。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant