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
    Regular Coder
    Join Date
    May 2003
    Location
    Chicago, IL
    Posts
    131
    Thanks
    3
    Thanked 0 Times in 0 Posts

    force long strings to wrap...how?

    Would anyone know of a way to force long strings to wrap...say at 40 characters using JavaScript?

    Say is I have a reoccurring class labeled class="location" I can get to each item with that following -
    Code:
    //getElementsByClass Written By: Dustin Diaz
            //http://www.dustindiaz.com/getelementsbyclass/
    
            //Slight minor modification by: Jon Christopher
            //http://www.MondayByNoon.com                   */
    
    		function getElementsByClass(node,searchClass,tag) {
    		    var classElements = new Array();
    		    var els = node.getElementsByTagName(tag); // use "*" for all elements
    		    var elsLen = els.length;
    		    var pattern = new RegExp("\\b"+searchClass+"\\b");
    		    for (i = 0, j = 0; i < elsLen; i++) {
    		         if ( pattern.test(els[i].className) ) {
    		             classElements[j] = els[i];
    		             j++;
    		         }
    		    }
    		    return classElements;
    		}
    		
    		function tree(num){
    		  var myEls = getElementsByClass(document,'location,'p');
                      // find string count and if over 40 insert <br />
                      // ???????????????????????????????????????
    }
    Or would this be better done server side?

  • #2
    Regular Coder
    Join Date
    Feb 2005
    Posts
    679
    Thanks
    0
    Thanked 16 Times in 15 Posts
    You can use the substring method:
    Code:
    // assumes less than 80
    if (myEls.length > 40) {
    str1 = myEls.substring(0,40);
    str2 = myEls.substring(40,myEls.length);
    alert(str1+'<br />'+str2);
    }

  • #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    http://javascript.about.com/library/blspline.htm has a script to wrap text at a specified number of characters that only breaks words that are longer than the specified length. All other new lines will be inserted between words.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

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