You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用string.match实现不截断单词的21字符字符串拆分?

Fixing Word-Safe String Splitting to Max 21 Characters

Got it, your current regex /.{1,21}/g splits the string into chunks of 21 characters max, but it doesn't respect word boundaries—hence why it's chopping "paragraphe" right in half. Let's fix that with two reliable approaches:

Approach 1: Regex with Word Boundary Checks

We can tweak the regex to only split at spaces or the end of the string, ensuring we never cut a word mid-way. Here's the code:

let string = "This is a new paragraphe that i'm writing to you";
// Match chunks up to 21 chars, ending at a space or string end
let lines = string.match(/(?:^| ).{1,20}(?= |$)/g)?.map(line => line.trim());
console.log(lines); // Output: ["This is a new", "paragraphe that i'm", "writing to you"]

Regex Breakdown:

  • (?:^| ): Start matching either at the string's beginning or right after a space (so we always start with a full word)
  • .{1,20}: Match 1-20 characters (since we accounted for the leading space, total length stays under 21)
  • (?= |$): Ensure the chunk ends right before a space or the string's end (no truncated words)
  • .map(line => line.trim()): Clean up leading spaces left from the matches

Approach 2: Manual Word-by-Word Building (More Reliable for Edge Cases)

If regex feels finicky (like handling apostrophes in words such as "i'm" or extra spaces), a manual loop is more straightforward and robust:

let string = "This is a new paragraphe that i'm writing to you";
const maxLineLength = 21;
const words = string.split(/\s+/); // Split into individual words
const lines = [];
let currentLine = "";

for (const word of words) {
  // Calculate length if we add this word to the current line (plus a space if needed)
  const nextLength = currentLine.length + (currentLine ? 1 : 0) + word.length;
  
  if (nextLength <= maxLineLength) {
    // Add word to current line (with space if line isn't empty)
    currentLine = currentLine ? `${currentLine} ${word}` : word;
  } else {
    // Push current line to array and start fresh with this word
    lines.push(currentLine);
    currentLine = word;
  }
}

// Don't forget to add the last line!
if (currentLine) lines.push(currentLine);

console.log(lines); // Output: ["This is a new", "paragraphe that i'm", "writing to you"]

Why This Works:

  • We split the original string into words first, so we never have to worry about cutting a word
  • We build each line incrementally, checking if adding the next word would exceed the 21-character limit
  • Handles edge cases like words longer than 21 characters (though all words are shorter in your example) by placing them alone in a line

内容的提问来源于stack exchange,提问作者EyTa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:48:49