首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我如何设置字符限制为100个而不分裂单词?

我如何设置字符限制为100个而不分裂单词?
EN

Stack Overflow用户
提问于 2014-10-22 12:08:15
回答 1查看 1.8K关注 0票数 2

我想每100个字符剪一根线而不切单词。

代码语言:javascript
运行
复制
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"]

那么,我怎样才能阻止它像它那样分裂单词呢?

EN

Stack Overflow用户

回答已采纳

发布于 2014-10-22 12:21:09

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

代码语言:javascript
运行
复制
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);
});

在这个例子中,我设置了40个字符的最大长度。

输出:

代码语言:javascript
运行
复制
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/

票数 4
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26507116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档