string.js有一段源码是什么意思?求教
发布于 11 年前 作者 lcyangily 5717 次预览 最后一次回复是 11 年前 来自 问答
string.js中有一段源码,截取字符串的,中文有点问题,看了源码,有一段不是很明白,求教:
var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
ps : str就是普通字符串 这段的目的是什么?
应小伙伴要求贴出方法全部:
truncate: function(length, pruneStr) { //from underscore.string, author: github.com/rwz
var str = this.s;
length = ~~length;
pruneStr = pruneStr || '...';
if (str.length <= length) return new this.constructor(str);
var tmpl = function(c){ return c.toUpperCase() !== c.toLowerCase() ? 'A' : ' '; },
template = str.slice(0, length+1).replace(/.(?=\W*\w*$)/g, tmpl); // 'Hello, world' -> 'HellAA AAAAA'
if (template.slice(template.length-2).match(/\w\w/))
template = template.replace(/\s*\S+$/, '');
else
template = new S(template.slice(0, template.length-1)).trimRight().s;
return (template+pruneStr).length > str.length ? new S(str) : new S(str.slice(0, template.length)+pruneStr);
}
7 回复
你能贴完整一点的代码吗?光这么看不太清楚
同不明白,代码贴全点也许能看出来。
@zry656565 @leapon 已经贴出
截取字符串,超过length长度的字符串用…代替
@151263 方法的目的是这个,但问的问题,不是这个,3Q
顶下,让高手看到,哈哈
我猜测你的代码来自:https://github.com/epeli/underscore.string 可以看到truncate函数现在的功能已经和原本不一样了,即楼主这里的代码实现是旧版本,现在被改为prune。 文档中如下写道:
搞清楚这两个函数的功能,具体深入到代码里,我建议你在源码里加一句代码:
然后再测一下这个函数,你应该就可以搞清楚上面这段代码在干嘛了