Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Loop through text and insert a break after X characters?

1. ## Loop through text and insert a break after X characters?

I have a string of text that is too long for the space I can put it in and need to loop through and put a <br> after 13 characters. The problem is I don't want to break a word in the middle, so if there is no space there, then it needs to go back to the last space and put the break there.

Anyone have any ideas how to do this? I started and then got lost as I started thinking it through...

Code:
```var text = 'this is my test text, it can be super long but I need to limit it';

if (text.length > 13){
for(i = 0; i < text.length; i++){

}
}```

• var text ='supercalifragelisticexpialadoscious. this is my test text, it can be super long but I need to limit it';

Code:
```String.prototype.chop= function(n){
var text=this, A=[], ax, tem;
while(text.length>n){
ax= text.substring(0,n).lastIndexOf(' ');
if(ax==-1) ax=n-1;
A[A.length]=text.substring(0,ax+1);
text=text.substring(ax+1);
}
if(text)A[A.length]=text;
return A;
}```
// test case-
alert(text.chop(13).join('\n'))

You can loop through the array and insert text nodes and line breaks for each iteration.

• The following code won't break words that are greater than n (13) characters.

Code:
```if(!Array.prototype.reduce)
Array.prototype.reduce = function(f /*, initial */) {
var i = 0, r = arguments.length > 1
? arguments[1]
: this[i++];
for(var n = this.length; i < n; ++i)
r = f.call(null, r, this[i], i, this);
return r;
};

String.prototype.chop = function(n) {
return this.split(' ').reduce(function(zs, w) {
if(!zs.length)
return [w];
z = zs.pop();
if(z.length + w.length < n)
zs.push(z + ' ' + w);
else
zs.push(z, w);
return zs;
}, []);
};```
Test Code:
Code:
```var text = "supercalifragelisticexpialadoscious. this is my test text, it can be super long but I need to limit it. 12 3 4 567";

alert(text.chop(13).join('\n'));```

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•