将文本分割,每n个字符添加一个新行并注意空格。

6
在编写警告和确认对话框文本时常见问题是在添加换行符之前需要键入的字符数。一些浏览器在一个点自动断开,另一些则在其他位置断开。因此,您需要猜测。有用的片段是一个Javascript函数,它以alert或confirm对话框的预期文本和字符长度作为输入,然后返回相同的输入字符串,其中仅在最接近所传递的字符长度的空间处添加了新行字符。这样,单词不会在中途被分开。
例如: 1. 分配一个变量给要用于警告或确认对话框的文本字符串,例如:var a =“My dog has fleas the quick brown fox jumps over the lazy dog etc”; 2. 运行该文本通过函数,例如:a = breakLines(a); //默认情况下,在每50个字符后换行或a = breakLines(a, 20); //每20个字符换行
运行函数后显示'a'的值,您将看到已在与指定字符位置最接近的空格处添加了换行符。例如如果您指定了20,则'a'将转换为以下内容:
'My dog has fleas\nthe quick brown fox\njumps over the lazy\ndog etc'
对于字符串中的每一行(行是以新行字符结尾的字符串部分),都会去掉两侧的空白。下面的代码片段使用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;
}

非常相关:http://stackoverflow.com/questions/27934616/get-array-of-sentences-from-lengthy-string-without-each-arrayindex-exceeding/27935244#27935244 - user663031
4个回答

4

没有参数验证的简短版本

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;
}

不太有用,因为它没有考虑单词的含义。 - user663031

0

可能吗?

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);
}

-1

这应该可以:

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");
}

-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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接