【问题标题】:Split a text to add a new line every n characters taking care of spaces拆分文本以每 n 个字符添加一个新行,注意空格
【发布时间】:2012-09-07 17:06:50
【问题描述】:

为警告和确认对话框编写文本时的常见问题:在添加换行符之前要输入的字符数。有些浏览器会在某一时刻自动中断,而另一些则在其他时刻自动中断。所以你只能猜测。有用的 sn-p 是一个 Javascript 函数,它将警报或确认对话框的预期文本和字符长度作为输入,然后返回相同的输入字符串,仅在空格最接近传入字符长度的位置添加新行字符。方式,单词不会中途分解。

示例:
1. 将 var 分配给要用于警报或确认对话框的文本字符串,例如:
var a = "我的狗有跳蚤,快速棕色狐狸跳过懒狗等";
2.通过函数运行文本,例如:
a = 断线(a); // 默认,每 50 个字符中断一次

a = breakLines(a, 20); // 每 20 个字符中断一次

在通过函数运行它后显示'a'的值,你会看到在你指定的每个地方都添加了换行符,在最靠近你指定的字符位置的空格字符处。例如,如果您指定 20,则“a”将转换为以下内容:

'我的狗有跳蚤\n敏捷的棕色狐狸\n跳过懒惰的\n狗等等'

对于字符串中的每一行(一行是字符串中以换行符结尾的部分),该行的两边都被修剪掉空白。下面的代码 sn-p 使用 jQuery $.trim() 函数来执行此操作,但还有其他方法可以在不使用 jQuery 库的情况下执行此操作,例如使用正则表达式。只需根据您的需要修改代码以使用替代方法。

这引出了我的问题:除了按照如下所示的方式做我想做的事情之外,是否有一种更简单、更紧凑的方法,例如可以利用正则表达式的方法?有接盘侠吗?

function breakLines(text, linelength)
{
 var linebreak = '\n';
 var counter = 0;
 var line = '';
 var returntext = '';
 var bMatchFound = false;
 var linelen = 50; // 50 characters per line is default

 if(linelength)
 {
  linelen = linelength;
 }

 if(!text){ return '';}
 if(text.length < linelen+1) { return $.trim(text);}

 while(counter < text.length)
 {
  line = text.substr(counter,linelen);
  bMatchFound = false;
  if (line.length == linelen)
  {
   for(var i=line.length;i > -1;i--)
   {
    if(line.substr(i,1)==' ')
    {
     counter += line.substr(0,i).length;
     line = $.trim(line.substr(0,i)) + linebreak;
     returntext += line;
     bMatchFound = true;
     break;
    }
   }

   if(!bMatchFound)
   {
    counter+=line.length;
    line = $.trim(line) + linebreak;
    returntext += line;
   }
  }
  else
  {
   returntext += $.trim(line);
   break; // We're breaking out of the the while(), not the for()
  }
 }

 return returntext;
}

【问题讨论】:

标签: javascript string replace split


【解决方案1】:

这个函数是递归的,而且更简单。它还处理文本中已经存在的换行符。它很短,没有循环。

function explode (text, max) {
        if (text == null) return '';
    if (text.length <= max) return text;
    const nextNewLine = /\n/.exec(text);

    const lineLength = nextNewLine ? nextNewLine.index: text.length;
    if (lineLength <=  max) {
        const line = text.substr(0, lineLength);
        const rest = text.substr(lineLength+1);
        return line + '\n'+  explode(rest, max);
    } else {
        let line = text.substr(0, max);
        let rest = text.substr(max);

        const res = (/([\s])[^\s]*$/.exec(line));
        if(res){ //
            line = text.substr(0, res.index);
            rest = text.substr(res.index+1);
        } else {
            line = line + "-";
        }
        return line + '\n'+  explode(rest, max);
    }
}

【讨论】:

    【解决方案2】:

    没有参数验证的短版

    function explode(str, maxLength) {
        var buff = "";
        var numOfLines = Math.floor(str.length/maxLength);
        for(var i = 0; i<numOfLines+1; i++) {
            buff += str.substr(i*maxLength, maxLength); if(i !== numOfLines) { buff += "\n"; }
        }
        return buff;
    }
    

    【讨论】:

    • 没用,因为它不考虑文字。
    【解决方案3】:

    应该这样做:

    function breaklines(str, n) {
        var lines = str.split(/\s+/), // explode on whitespaces
            n = +n || 50;
        var res = [];
        for (var i=0; i<lines.length; ) {
            for (var l = 0, line = []; l + lines[i].length <= n; i++) {
                l += 1 + lines[i].length;
                line.push(lines[i]);
            }
            res.push(line.join(" "));
        }
        return res.join("\n");
    }
    

    【讨论】:

      【解决方案4】:

      也许吧?

      function breadLines( str, len )
      {
          var len = len || 50, i, j, lines, count, lineBreak = '\n', out = [];
      
          if ( str.length < len )
              return str;
      
          lines = str.split(/\s+/);
      
          for ( i=0, j=0, count=lines.length; i<count; i++ )
          {
              if ( ( out[j] + lines[i] ).length > len )
                  j++, out.push("");
      
              out[j] += lines[i];
          }
      
          return out.join(lineBreak);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-06-25
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        相关资源
        最近更新 更多