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

技术问询:实现每n个字符插入 且不拆分单词(含字符计数)

Hey there! Let's work through this problem together—since you mentioned you're not a full web dev and only know a bit of JavaScript, I'll keep things simple and explain every step clearly.

First, let's restate your requirements to make sure I got them right:

  • Insert   (non-breaking space) into text every n characters
  • Never split a word in the middle when inserting
  • The   itself counts as 1 character towards the next character count

Here's a straightforward JavaScript function that does exactly this, with comments to walk you through what's happening:

function insertNonBreakingSpaces(text, maxChars) {
  // Use an array to build our processed text (faster than string concatenation)
  const result = [];
  // Track how many characters we've counted so far (including   as 1)
  let currentCharCount = 0;
  let index = 0;

  while (index < text.length) {
    const currentChar = text[index];
    
    // Add the current character to our result
    result.push(currentChar);
    // Increment our count (each regular character counts as 1)
    currentCharCount++;

    // Check if we've hit or exceeded our max character limit
    if (currentCharCount >= maxChars) {
      // Find the next space to avoid splitting a word
      let nextSpaceIndex = text.indexOf(' ', index + 1);
      // If there's no more spaces, we're at the end of the text
      if (nextSpaceIndex === -1) {
        nextSpaceIndex = text.length;
      }

      // Add all remaining characters of the current word to the result
      result.push(text.slice(index + 1, nextSpaceIndex));
      // Jump our index to the position after the space
      index = nextSpaceIndex;

      // Only insert &nbsp; if we're not at the end of the text
      if (index < text.length) {
        result.push('&nbsp;');
        // Reset the count to 1 (since &nbsp; counts as one character)
        currentCharCount = 1;
      } else {
        currentCharCount = 0;
      }
    } else {
      // Move to the next character if we haven't hit the limit yet
      index++;
    }
  }

  // Join the array back into a single string and return it
  return result.join('');
}

How to use this function

Let's say you want to insert &nbsp; every 10 characters. You'd call it like this:

// Example product description text
const originalText = "Premium cotton t-shirt available in 5 colors, sizes S to XXL";
// Process the text with max 10 characters per segment
const processedText = insertNonBreakingSpaces(originalText, 10);
// Output: "Premium&nbsp;cotton&nbsp;t-shirt&nbsp;available&nbsp;in 5&nbsp;colors,&nbsp;sizes S&nbsp;to XXL"
console.log(processedText);

If you're using this with your HTML editor, you can hook it up to get the editor's content, process it, and put it back:

// Replace 'product-list-editor' with your editor's actual ID
const editor = document.getElementById('product-list-editor');
// Process the content (using 10 as the max character example)
editor.value = insertNonBreakingSpaces(editor.value, 10);

A quick note

If your HTML editor's content includes HTML tags (like <b>, <p>, etc.), this function will process the text inside those tags too. If you need to ignore HTML tags entirely, we'd need to add extra logic to skip them—but since you mentioned this is for product lists, I assume the content is mostly plain text or simple formatting, so the basic function should work fine.

Let me know if you need help tweaking this to fit your specific setup!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:06:54