繁体   English   中英

在 n 个字符之前的最后一个字符的字符串中添加换行符

[英]Add line break in string on last character before n characters


首先,这可能措辞不好,因为我不知道如何用语言表达我想要的
假设我有这个画布(我正在使用node-canvas ),我想让它显示来自用户输入的文本。 但是,我这样做的方式将字符数限制为 36-38(不是在寻找解决方案)。 因此,我使用 Regex textstr.match(/.{1,32}/g)制作了一个脚本,该脚本每 32 个字符拆分字符串(为了安全起见),计算新的画布高度,然后join("\\n")当需要打印字符串时。 但是,当收到关于此的反馈时,我意识到最好沿字符串中的最后一个空格拆分并在那里添加换行符,但我很困惑如何做到这一点。
我目前的代码是这样的:

textStr = "123456789 01234567890 123456789012 34567890"
var splitStr 
    if(textstr.length > 32){
    if(textstr.substring(1,32).includes(" ")){ //1,32 so it won't bug out if the first character is a space
//splitStr = textstr.something(test)
    
    } else  {
      splitStr = textstr.match(/.{1,32}/g)
      
    }
    } 
    //canvas initialization blah blah blah
    //load fonts yada yada yada
    ctx.fillText(splitStr.join("\n"), 20, 55) 

我想知道是否有某种我可以使用的正则表达式。 任何帮助/反馈/常识表示赞赏

这个解决方案有点复杂,可以进行一些简化。 但是,它应该让您大部分时间都在那里。

const input = "123456789 01234567890 123456789012 34567890 11444444444 424124  1234124124121 4444444444444444444444444444444444444444444444444444444444444444444444";

const split = (value, width) => {
  const stack = value.split(' ').reverse();
  const results = [];
  let builder = "";
  
  while (stack.length > 0) {
    const item = stack.pop();
    
    if (item.length > width) { // is the current chunk already larger than  our desired width?
      if (builder !== "") { // we have to push our buffer too
        results.push(builder);
        builder = "";
      }
        
      results.push(item);
    } else {
      const line = builder === ""
        ?   item
        : `${builder} ${item}`;
        
      if (line.length > width) { // is our new line greater than our width?
        stack.push(item); // push the item back, since consuming it would make our line length too long. we let the next iteration consume it.              results.push(builder); // push the buffer into our results.
        builder = "";
      } else if (stack.length === 0) { // is this the last element? just add it to the results.
        results.push(line);
      } else {
        builder = line; // update our buffer to the current appended chunk.
      }
    }
  }
  
  return results;
};

split(input, 32).forEach((c) => console.log(c, c.length));
split(input, 32).join("\n");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM