根据JavaScript中的长度截断多行文本

时间:2014-09-12 21:55:41

标签: javascript substitution

我有以下JavaScript代码根据其长度截断字符串并添加" ..."最后。

var elem = document.createElement('lengthDiv');
var text = "text to truncate";
elem.style.position = "absolute";
elem.style.whiteSpace = "nowrap";
elem.style.font = "helvetica";
elem.innerHTML = text;
document.documentElement.appendChild(elem);
var length = elem.clientWidth;
if (length > 298) {
    var i = 1;
    elem.innerHTML = '';
    while (elem.clientWidth < 298 && i < text.length) {
        elem.innerHTML = text.substr(0, i) + '...';
        i++;
    }
}
if (elem.clientWidth < 298 && i > 1) {
    while (elem.clientWidth < 298) {
        elem.innerHTML = elem.innerHTML + '.';
    }
}
var endresult = elem.innerHTML;

如何使此代码适用于影响多行文本的单个文本块? 例如,我想转此:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

进入(大致):

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed... 
Ut enim ad minim veniam, quis nostrud exercitation ullamco l...
Duis aute irure dolor in reprehenderit in voluptate velit es...
Excepteur sint occaecat cupidatat non proident, sunt in culp...

我需要它与仅JavaScript ,没有JQuery或任何其他库。

1 个答案:

答案 0 :(得分:0)

我会拆分你的字符串,然后截断该数组中的每个项目。这会给你截断的句子。

var res = text.split(".");

for (i = 0; i < res.length; i++) { 
        // truncate each sentence
}