Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - How can I set a character limit of 100 without splitting words?

I want to cut a string every 100 characters without cutting up words.

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);

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

So how can I prevent it from splitting words like it did?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Interesting question. I will propose one more implementation of how you can use just array methods, combination of split + reduce:

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...