SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: Regex question

  1. #1
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regex question

    I'm trying to think of a pattern that will work kind of like php's wordwrap function.

    So for example, for a given character length, I want to split a string into separate groups, but without breaking a word.

    So for example, for a length of 20 characters:

    var testString = "Building Walls Using SIPs, Structural Insulated Panels";
    testString.split(pattern);

    would return:

    array("Building Walls Using", "SIPs, Structural", "Insulated Panels");

    Any ideas?

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Search google for javascript word-wrap
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    String.prototype.chunk= function(n,sep){
          n= n || 80;
          sep= sep||'- ';
          n2= n-sep.length;
          var Rx= RegExp('(\\S{'+n+',})','g');
          var str= this.replace(Rx, function(toolong){
                return toolong.replace(/(\W+) */g,'$1 ');
          })
          str= str.replace(/\s+/,' ');
          var A= [], s, ax;
          while(str.length >n){
                s= str.substring(0,n);
                ax= s.lastIndexOf(' ');
                if(ax!= -1){
                      A.push(s.substring(0,ax));
                      str= str.substring(ax+1);
                }
                else{
                      ax= str.indexOf(' ');
                      if(ax==-1) ax= str.length;
                      s= str.substring(0,ax);
                      while(s.length >n2){
                            A.push(s.substring(0,n2) +sep);
                            s= s.substring(n2);
                      }
                      str= s+ str.substring(ax);
                }
          }
          A.push(str);
          return A;
    }
    //test code
    var str='Like most code, the better part of this one is for situations '+
    'that rarely come up- input that is not spaced to fit in a chunk.'+
    'You could add more logic for hyphenation, if you need.';

    alert(str.chunk(30).join('\n'));
    Last edited by mrhoo; Mar 13, 2008 at 15:25. Reason: accounted for long strings with no spaces at all


Bookmarks

Posting Permissions

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