如何在JavaScript中尊重单词的字符串成块? [英] How can I chunk a string in JavaScript respecting words?

查看:57
本文介绍了如何在JavaScript中尊重单词的字符串成块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的文本块,我想将其拆分为一个数组,每个元素为一行,最多50个字符.如果字符串包含 \ r \ n ,我希望它本身就是一个元素(而不是另一个字符串的一部分).我对如何做到这一点感到困惑.

I have a large block of text and I want to split that into an array with each element being one line of up to 50 characters. If the string contains a \r or \n, I want that to be an element itself (not part of another string). I'm a bit perplexed on how to do this.

我尝试过

lines = newVal.match(/^(\r\n|.){1,50}\b/g)

我也尝试过下划线/lodash _.chunk ,但这显然忽略了单词.但这只给了我第一场比赛.请帮忙.

I've also tried underscore / lodash _.chunk but that ignores words obviously. But this gives me only the first match. Please help.

推荐答案

尝试一下:

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

这将首先通过换行符将文本分割成一个数组,然后继续细分数组中的长行,并保留单词.

This will first split the text into an array by your newlines, then go and further break up the long lines in the array, maintaining the words.

这篇关于如何在JavaScript中尊重单词的字符串成块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆