...

View Full Version : Loop through text and insert a break after X characters?



imanta
08-15-2008, 07:34 PM
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...



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++){

}
}

mrhoo
08-15-2008, 09:06 PM
var text ='supercalifragelisticexpialadoscious. this is my test text, it can be super long but I need to limit it';


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.

Trinithis
08-15-2008, 10:53 PM
The following code won't break words that are greater than n (13) characters.



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:


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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum