regex 如何将文本自动换行到给定的字符行长度?

8aqjt8rx  于 2023-06-25  发布在  其他
关注(0)|答案(4)|浏览(74)

我想文字 Package 成一个数组的行(短语/行)与N个字符的最大长度的文本。如果一个单词大于最大行长度,则该单词应被剪切到该长度。

编辑:n个字符的最大长度永远不会小于100个字符,我用了10个字符来向你展示我的代码无法正常工作

const sentence =`Wake has three meanings as a noun, and, yes, just about as many meanings as a verb! So get set. To wake is come out of sleep, a verb you'll recognize from "Wake up! You're asleep at the wheel!" You can wake feelings, as well as the people who are having them. The wake before the funeral caused Mike to wake from his depression and decide to live life to the fullest. His first act was to water ski; he eventually mastered staying upright while crossing the wake of the boat that was towing him.`

// shorten with max characters of 10
console.log(shorten(sentence, 10));

function shorten(str, maxLen) {

  if(str.length <= maxLen) return [str];
  let max, min = 0, i = 1;
  const result = [];
    while (maxLen * i < str.length) {
    max = str.lastIndexOf(' ', maxLen * i);
    result.push(str.substr(min, max));
    min = max + 1;
    i++;
    }
  return result;
 
}

问题是我的代码不能像你看到的那样正常工作。

所需输出为:

["Wake has", "three", "meanings", "as a noun,", ...]  // each one has length of : 8 - 5 - 8 - 10
b5buobof

b5buobof1#

您可以将regex (?=\S).{0,99}\S(?!\S)|\S{100}.matchAll结合使用,以查找所需的符号块(参数等于100)。
这里正则表达式匹配:

  • (?=\S).{0,99}\S(?!\S)一个到一百个符号的块,以非空白符号开始和结束,后跟空白或行尾:
  • (?=\S)检查第一个符号是否为非空白,
  • .{0,99} 0到99之间的任何符号,除换行符外,
  • \S将最后一个符号匹配为非空白,
  • (?!\S)检查匹配后是否有空格符号(以防止在单词中间换行)
  • \S{100}一百个后续非空白符号:对于非常长的字的情况,其跨越最大预期行长度。

代码示例:

const sentence =`Wake has three meanings as a noun, and, yes, just about as many meanings as a verb! So get set. To wake is come out of sleep, a verb you'll recognize from "Wake up! You're asleep at the wheel!" You can wake feelings, as well as the people who are having them. The wake before the funeral caused Mike to wake from his depression and decide to live life to the fullest. His first act was to water ski; he eventually mastered staying upright while crossing the wake of the boat that was towing him.`

console.log(wrapLines(sentence, 100));

function wrapLines(str, maxLen){
    let reg = new RegExp('(?=\\S).{0,'+(maxLen-1)+'}\\S(?!\\S)|\\S{'+maxLen+'}', 'gm')
    console.log(reg)
    return Array.from(str.matchAll(reg), (m) => m[0]);
}
1hdlvixo

1hdlvixo2#

据我所知,这项任务是用等宽字体对文本进行自动换行。
不知何故,它的工作:

const sentence = `Some-long-string-should-be-cut-to-10 Wake has three         meanings as a noun, and, yes, just about as many meanings as a verb! So get set. To wake is come out of sleep, a verb you'll recognize from "Wake up! You're asleep at the wheel!" You can wake feelings, as well as the people who are having them. The wake before the funeral caused Mike to wake from his depression and decide to live life to the fullest. His first act was to water ski; he eventually mastered staying upright while crossing the wake of the boat that was towing him.`

// shorten with max characters of 10
console.log(shorten(sentence, 10).map(str => str + ': ' + str.length));

function shorten(str, maxLen) {

    const phrases = [];
    let phrase = '';
    let word = '';

    const addWord = () => {
        if(word){
            phrase.length + word.length >= maxLen && addPhrase();
            phrase += (phrase ? ' ' : '') + word;
            word = '';
        }
    };

    const addPhrase = () => {
        if(phrase){
            phrases.push(phrase.length > maxLen ? phrase.substring(0, maxLen) : phrase);
            phrase = '';
        }
    };

    for (let i = 0; i < str.length; i++) {
        const c = str[i];
        c === ' ' ? addWord() : word += c;
    }

    addWord();
    addPhrase();

    return phrases;
}
3htmauhk

3htmauhk3#

改成

const sentence = `Wake has three meanings as a noun, and, yes, just about as many meanings as a verb! So get set. To wake is come out of sleep, a verb you'll recognize from "Wake up! You're asleep at the wheel!" You can wake feelings, as well as the people who are having them. The wake before the funeral caused Mike to wake from his depression and decide to live life to the fullest. His first act was to water ski; he eventually mastered staying upright while crossing the wake of the boat that was towing him.`;

console.log(shorten(sentence, 10));

function shorten(str, maxLen) {
  if (str.length <= maxLen) return [str];
  
  const result = [];
  let startIndex = 0;
  let endIndex = maxLen;
  
  while (endIndex < str.length) {
    while (str[endIndex] !== ' ' && endIndex > startIndex) {
      endIndex--;
    }
    
    result.push(str.substring(startIndex, endIndex));
    startIndex = endIndex + 1;
    endIndex = startIndex + maxLen;
  }
  
  result.push(str.substring(startIndex));
  
  return result;
}
bwleehnv

bwleehnv4#

你可以这样做,如果你没有大量的文本,这可能是可行的:

function textSplitter(text, maxLength){
    var currentPos = 0;
    var result = [];
    while(currentPos < text.length){
        const probe = text.substring(currentPos, currentPos+maxLength); // take max length
        const lastSpace = probe.lastIndexOf(" "); // track back to last space
   
        const item = probe.substring(0, lastSpace); // take what you want
        result.push(item); // store it
        currentPos += item.length + 1; // 1 is the space
    }

    return result;
}

这是未经测试的代码,我希望你在某些地方需要+1或-1,但这是一个例子。
(If有人想调整它并修复它,请随意这样做)。

相关问题