• home
  • forum
  • my
  • kt
  • download
  • Reduce a string to a certain length

    Author: 2007-06-12 11:49:23 From:

    This morning i needed to reduce any given string to a certain length and then place a pattern at the end of the string, in this case a simple '....' but the reduction had to take into account full words, meaning, i didnt want to just split the string in any old place and leave parts of a word in the final string. So i created this little String Exstension which i thought may come in useful for some other people! Seems to work great for me....

    You pass this method of the String object, a length to cut the string down to, and a pattern that you want to be returned at the end of the string:


    this.onEnterFrame=function()
    String.prototype.reduce=function(l,p)
    {
    if(this.length<=l) return this;
    var words=this.split(" ")
    var numWords=words.length
    var output=[]
    var ol,cWord,w
    for(w=0;w {
    cWord=words[w]
    cwl=cWord.length
    if((ol+cwl)<=l)
    {
    output.push(cWord)
    ol+=cwl+1
    }
    else break
    }
    return output.join(" ")+(this.length>l) ? p
    }


    And here is how you would use this method:


    rhyme="Bah bah, black sheep, have you any wool?"
    cutRhyme=rhyme.reduce(22,"...")


    For examples sake:


    trace(cutRhyme);


    Outputs:


    this.onEnterFrame=function()
    Bah bah black sheep...

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      3D (20)
      Math Physics (14)
      3rd Party (5)
      Navigation (60)
      Actionscripting (26)
      Optimization (16)
      Animation (32)
      Projector (9)
      Audio (46)
      Special Effects (112)
      Backend (25)
      Text Effects (65)
      Drawing (18)
      Tips and Techniques (41)
      Dynamic Content (25)
      Tricks (6)
      Games (66)
      Utilities (19)
      Getting Started (71)
      Video (10)
      Interactivity (21)
      Web Design (22)

    New

    Hot