Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Apr 2005
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

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

  • #2
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    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.

  • #3
    Regular Coder
    Join Date
    Jun 2007
    Location
    USA
    Posts
    527
    Thanks
    26
    Thanked 74 Times in 72 Posts
    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'));
    Trinithis


  •  

    Posting Permissions

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