admin管理员组文章数量:1316844
Common problem when writing text for alert and confirm dialogs: number of characters to type before adding a newline character. Some browsers auto-break at one point, others at others. So you are left guessing. Useful snippet is a Javascript function that takes as input the alert or confirm dialog's intended text and a char length, then returns the same input string only with new line chars added at the positions with spaces closest to the char length passed in. That way, words are not broken up mid-way.
Example:
1. Assign a var to a string of text you want to use for the alert or confirm dialog box, eg.:
var a = "My dog has fleas the quick brown fox jumps over the lazy dog etc";
2. Run the text through the function, for example:
a = breakLines(a); // Default, break every 50 chars
or
a = breakLines(a, 20); // Break every 20 chars
Display the value of 'a' after running it through the function and you will see line breaks have been added at every place you specified at the space character closest to the character place you specified. For example if you specified 20, 'a' would be converted to the following:
'My dog has fleas\nthe quick brown fox\njumps over the lazy\ndog etc'
For each line in the string (a line is a portion of the string ending in a new line character), the line is trimmed of whitespace on both sides. The code snippet below uses the jQuery $.trim() function to do this but there are other ways to do so without using the jQuery library, such as with regexp. Just modify the code as you want to to use alternate means.
This leads to my question: Aside from doing what I want to do the way I have done it as shown below, is there an easier more pact way of doing it, something that for example can leverage regexp? Any takers?
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;
}
Common problem when writing text for alert and confirm dialogs: number of characters to type before adding a newline character. Some browsers auto-break at one point, others at others. So you are left guessing. Useful snippet is a Javascript function that takes as input the alert or confirm dialog's intended text and a char length, then returns the same input string only with new line chars added at the positions with spaces closest to the char length passed in. That way, words are not broken up mid-way.
Example:
1. Assign a var to a string of text you want to use for the alert or confirm dialog box, eg.:
var a = "My dog has fleas the quick brown fox jumps over the lazy dog etc";
2. Run the text through the function, for example:
a = breakLines(a); // Default, break every 50 chars
or
a = breakLines(a, 20); // Break every 20 chars
Display the value of 'a' after running it through the function and you will see line breaks have been added at every place you specified at the space character closest to the character place you specified. For example if you specified 20, 'a' would be converted to the following:
'My dog has fleas\nthe quick brown fox\njumps over the lazy\ndog etc'
For each line in the string (a line is a portion of the string ending in a new line character), the line is trimmed of whitespace on both sides. The code snippet below uses the jQuery $.trim() function to do this but there are other ways to do so without using the jQuery library, such as with regexp. Just modify the code as you want to to use alternate means.
This leads to my question: Aside from doing what I want to do the way I have done it as shown below, is there an easier more pact way of doing it, something that for example can leverage regexp? Any takers?
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;
}
Share
Improve this question
edited Sep 14, 2012 at 15:27
sp00m
48.8k31 gold badges150 silver badges259 bronze badges
asked Sep 14, 2012 at 14:00
Matt CampbellMatt Campbell
2,2371 gold badge24 silver badges38 bronze badges
1
- Very related: stackoverflow./questions/27934616/… – user663031 Commented Jan 8, 2016 at 7:54
4 Answers
Reset to default 4Short version with no params validation
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;
}
Maybe ?
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);
}
This should do it:
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");
}
This function is recursive and a lot more simple. It also deals with newlines already being in the text. It's short and without loops.
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);
}
}
本文标签: javascriptSplit a text to add a new line every n characters taking care of spacesStack Overflow
版权声明:本文标题:javascript - Split a text to add a new line every n characters taking care of spaces - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742013336a2413304.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论