如何在不分割单词的情况下将字符数限制设置为100?

时间:2014-10-22 12:08:15

标签: javascript string substring string-split

我想每100个字符剪一个字符串而不会删掉字词。

var TmpArray=[];
var str = 'this string will be cut up after every 100 characters but it will cut into words';
str=str.replace(/[^a-z A-Z0-9]+/g, '');
str = str.replace(/\s{2,}/g, ' ');
var sp=(str.match(new RegExp(" ", "g")) || []).length;
var max=100;
//Spaces will be converted into %20 (later) so each space must count as 3 characters.
var FoundSpaces=sp*3;
var tmp=max-FoundSpaces;
var cut=str.match(new RegExp('.{1,'+tmp+'}', 'g'));
for (i = 0; i < cut.length; i++){
    TmpArray.push(cut[i]);
}
console.log(TmpArray);

输出:["this string will be cut up after every 100 characters b", "ut it will cut into words"]

那么如何防止它像分裂那样分裂?

1 个答案:

答案 0 :(得分:4)

有趣的问题。我将再提出一个如何使用数组方法的实现,split + reduce的组合:

&#13;
&#13;
var str = 'This example of the string that we want to split by spaces only making sure that individual chunk is less or equal to specified number.';

// Split by spaces
str.split(/\s+/)

// Then join words so that each string section is less then 40
.reduce(function(prev, curr) {
    if (prev.length && (prev[prev.length - 1] + ' ' + curr).length <= 40) {
        prev[prev.length - 1] += ' ' + curr;
    }
    else {
        prev.push(curr);
    }
    return prev;
}, [])

// Print for testting
.forEach(function(str) {
    console.log(str + ' ' + str.length);
});
&#13;
&#13;
&#13;

对于此示例,我将最大长度设置为40个字符。

输出:

This example of the string that we want 39
to split by spaces only making sure that 40
individual chunk is less or equal to 36
specified number. 17

又一个演示:http://jsfiddle.net/9tgo6n1t/