如何在不拆分单词的情况下将字符限制设置为100
How can I set a character limit of 100 without splitting words?
我想每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"]
那么,我该如何防止它像以前那样分裂单词呢?
有趣的问题。我将再提出一个如何仅使用数组方法的实现,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);
});
在这个例子中,我设置了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/
相关文章:
- 使用正则表达式将输入格式设置为单字符逗号、单字符逗号等
- Rails 4 - 设置文本区域的字符数限制
- 如何使用javascript获取&使用字符偏移量设置插入符号位置
- 使用jquery为html元素文本的每个字符设置动画
- 打破ng中的字符数组,重复并设置每个字符自己的输入标记
- 如何指定输入元素中允许的最大字符数 - 设置 maxlength 属性是否足够
- 如何在文本框点击事件中设置文本框中字符的第一个位置---Chrome问题
- Firebase REST API - 如何设置字符编码
- 在输入框中设置“最小”字符输入抛出 javascript
- 需要帮助使用 JavaScript 设置最小字符数
- 将滑块输入值设置为闪亮字符
- 如何设置文本框的格式和允许的字符
- 如何为同一输入框中的字符设置不同的字体粗细
- 如何在不拆分单词的情况下将字符限制设置为100
- 使用非法字符设置DIV ID名称
- 如何在javascript中使用UTF-8字符设置Safari浏览器标题
- 我们可以对通过CKeditor输入的字符设置一个限制吗?
- 如何基于前三个字符设置元素样式
- 检测元素的innerHTML的最后一个字符是否为"1",如果是,下划线并将最后一个字符设置为绿色,并
- 如何为控制字符设置按键陷阱