如何将字符串分块到JavaScript单词中?
我有一大块文本,我想把它分割成一个数组,每个元素是一行,最多50个字符。如果字符串包含一个如何将字符串分块到JavaScript单词中?,javascript,string,Javascript,String,我有一大块文本,我想把它分割成一个数组,每个元素是一行,最多50个字符。如果字符串包含一个\r或\n,我希望它是一个元素本身(而不是另一个字符串的一部分)。我对怎么做有点困惑 我试过了 lines = newVal.match(/^(\r\n|.){1,50}\b/g) 我也尝试过下划线/lodashu2;.chunk,但这显然忽略了单词。 但这只给了我第一场比赛。请帮助。尝试使用String.prototype.split(),循环时,数组.prototype.some(),数组.proto
\r
或\n
,我希望它是一个元素本身(而不是另一个字符串的一部分)。我对怎么做有点困惑
我试过了
lines = newVal.match(/^(\r\n|.){1,50}\b/g)
我也尝试过下划线/lodashu2;.chunk
,但这显然忽略了单词。
但这只给了我第一场比赛。请帮助。尝试使用
String.prototype.split()
,循环时,数组.prototype.some()
,数组.prototype.filter()
,字符串.prototype.slice()
,数组.prototype.splice()
试试这个:
result = lines.split(/(?=(\r\n))/g);
result.forEach(function(item,index,arr) {
if(item.length > 50) {
var more = item.match(/.{1,50}\b/g);
arr[index] = more[0];
for(var i=1; i<more.length; ++i) {
arr.splice(index+i, 0, more[i]);
}
}
});
result=lines.split(/(?=(\r\n))/g);
结果.forEach(功能(项目、索引、arr){
如果(项目长度>50){
var more=item.match(/.{1,50}\b/g);
arr[index]=更多[0];
对于(var i=1;i首次拆分
newVal.split(/\b|(?=\n)|(?=\r)/)
然后加入
.reduce(function(accum,x,i){
if(x=="\n"
|| x=="\r"
|| (accum[accum.length-1]+x).length>50
){
accum.push(x);
} else {
accum[accum.length-1]+=x;
}
return accum;
},[])
我没有处理单词长度超过50个字符的情况,但这只是因为它没有真正明确说明应该发生什么这里只是ES6功能方法的一个示例(不受意图影响):
let _range=(count,step)=>Array.apply(null,Array(count)).map((u,i)=>(i*step));
让splitByLimit=函数(limit=10,string=''){
让长度=string.length;
if(长度字符串切片(位置,位置+限制));
}
};
让getLines=函数(字符串=“”,限制=10){
设splitted=string.split(/\r |\n/);
让byLimit=splitByLimit.bind(null,limit);
让展平=(备忘录,项目)=>memo.concat(项目);
返回splitted.map(byLimit).reduce(展平,[]);
};
.您需要保留现有换行符吗?是的。我需要保留现有换行符扫描您给我们一些输入/输出的示例?使用split()而不是match()我的意思是<代码>行>代码>变量是指你的文本块,如果你不知道,抱歉,在你的例子中,它被称为“代码> NeValue<代码>。但是……这将不尊重单词边界。我不想在单词的中间断开存储在<代码> ARR < /代码>中的最后一个数组。在循环之后,最终的拆分数组将在<代码> RES中找到。要明确, ARR 指的是同一个数组,但它是为循环的目的声明的范围变量。这不尊重单词边界。我不想在单词的中间断裂。
.reduce(function(accum,x,i){
if(x=="\n"
|| x=="\r"
|| (accum[accum.length-1]+x).length>50
){
accum.push(x);
} else {
accum[accum.length-1]+=x;
}
return accum;
},[])
let _range = (count, step) => Array.apply(null, Array(count)).map((_, i) => (i * step));
let splitByLimit = function(limit = 10, string = '') {
let length = string.length;
if (length <= limit) {
return [string];
} else {
let positions = _range(Math.ceil(length / limit), limit);
return positions.map(pos => string.slice(pos, pos + limit));
}
};
let getLines = function(string = '', limit = 10) {
let splitted = string.split(/\r|\n/);
let byLimit = splitByLimit.bind(null, limit);
let flatten = (memo, item) => memo.concat(item);
return splitted.map(byLimit).reduce(flatten, []);
};