如何将行分割为x个字符或更少,并且仅在空格处(“ ”)进行分割?

4
我正在创建一个程序,该程序将在x个字符处分割行,并且仅在空格(" ")处进行分割。
输入段落:

那天没有散步的可能性。事实上,我们早上在没有叶子的灌木丛中漫步了一个小时;但自午餐以来(里德夫人在没有客人时提前用餐),寒冷的冬风带来了如此阴沉的云和雨

输入分割字符:30
现在我得到的输出是这样的:
var textArray = ["There was no possibility of ta","king a walk that day. We had b","een wandering, indeed, in the ","leafless shrubbery an hour in ","the morning; but since dinner ","(Mrs. Reed, when there was no ","company, dined early) the cold"," winter wind had brought with ","it clouds so sombre, and a rai","n so "]`

但我只想在空格处进行分割 (). 它会在指定字符数之前的最后一个空格处进行分割。

我希望输出结果如下:

var textArray = ["There was no possibility of", "taking a walk that day. We", "had been wandering, indeed, in", "the leafless shrubbery an hour", "in the morning; but since", "dinner (Mrs. Reed, when there", "was no company, dined early)", "the cold winter wind had", "brought with it clouds so", "sombre, and a rain so", "penetrating, that further", "out-door exercise was now out", "of the question."]`

我尝试了这段代码:

我尝试了这段代码:

function textToArray() {
       var str = document.getElementById('stringg').value;
       var strArr = [];
       var count = parseInt(document.getElementById('numberOfWords').value, 10) || 1;

       for (var i = 0; i < str.length; i = i + count) {
            var j = i + count;
            strArr.push(str.substring(i,j));
       }
}

你已经尝试过什么了吗?你有一些代码可以展示给我们吗? - Jordumus
为什么不直接按单词拆分呢?30个字符大约等于5或6个单词。通过空格将整个字符串拆分并获取每5个索引。 - TheValyreanGroup
2
请检查我的更新问题@Jordumus。 - don
加入一点点代码,突然就能得到三个答案,这不是很有趣吗? ;) - Jordumus
4个回答

4
你可以使用数组.reduce:

var str = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";
str = str.split(' ').reduce((m, o) => {
    var last = m[m.length - 1];
    if (last && last.length + o.length < 30) {
        m[m.length - 1] = `${last} ${o}`;
    } else {
        m.push(o);
    }
    return m;
}, []);
console.log(str);


4
尝试这种方法(注释内联

var input = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";

function splitter(input, maxChars) {
  var output = [];
  output.push( input.split(" ").reduce(function(a, b) {
    if (a.length + b.length < maxChars) {
      a += " " + b; //if comnined length is still not execeeding add it a
    } else {
      output.push(a); //if combined less is exceeding the maxchars then push the last sentence to output
      a = b;
    }
    return a;
  })); //push the residue to output
  return output;
}

console.log( splitter( input, 30 ) );


1
我会循环遍历文本,判断当前字符是否为有效的分隔符,如果不是,则寻找最近的空格。

const
  input = 'There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so';
  
function splitText(text, maxLength = 30) {
  const 
    result = [];

  // Keep looping till the input string is empty.
  while (text !== '') {
    // Initialize endIndex to the specified max length for the substring.
    let 
      endIndex;
      
    // A: If the max length is more than the remaining text length, adjust the 
    //    end index so it coincides with the remaining text length.
    // B: Else check if the character at the max length is NOT a space, in this 
    //    case go looking to a space as close to the max length as possible.
    if (maxLength > text.length) {  // [A]
      endIndex = text.length;
    } else if (text.substring(maxLength, 1) !== ' ') { // [B}
      endIndex = text.lastIndexOf(' ', maxLength);
    } else {
      endIndex = maxLength;
    }
    // Take the string with the determined length and place it in the result array.
    result.push(text.substring(0, endIndex));
    // Adjust the input string, remove the part that was just pushed into the result.
    text = text.substr(endIndex).trim();
  }

  return result;
}


console.log(splitText(input));


我对各种解决方案的性能很好奇,所以我制作了一个JSPerf来测试它们。我从我的代码中删除了注释,以免占用不必要的解析时间。请参见此处的基准测试:https://jsperf.com/splitbywholewords/1 - Thijs

0
你可以取数组的最后一个元素并检查其长度是否小于或等于预期长度,然后将临时字符串连接到结果集中,否则将最后一个字符串和实际项连接到结果集中。

var string = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";

string = string.split(' ').reduce(function (r, a) {
    var last = r.pop() || '',
        temp = last + (last && ' ') + a;
    return r.concat(temp.length <= 30 ? temp : [last, a]);
}, []);

console.log(string);
.as-console-wrapper { max-height: 100% !important; top: 0; }

在 ES6 中,您可以使用 rest 运算符采用递归方式,并使用第一个参数添加字符串,直到它达到所需的长度,然后返回该部分。

function join(a, b, ...rest) {
    if (!b) {
        return [a];
    }
    return a.length + b.length < 30
        ? join(a + ' ' + b, ...rest)
        : [a, ...join(b, ...rest)];
}

var string = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";

console.log(join(...string.split(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接