Stay Connected

Get Your Site Submitted for Free in the World's Largest B2B Directory!

Email Address:
* URL:
*
*Indicates Mandatory Field

Terms & Conditions

Navigation

Home

About

Tutorials

Featured Sites

Newsletter

FLADownloads

Forum

Jayde

iEntry

Advertise

Contact Us







Reduce A String

By Guy Watson
Expert Author
Article Date: 2004-05-24

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:

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:

Bah bah black sheep...

About the Author:
Guy Watson (or FlashGuru as he is also known) has been an active, well recognized figure in the Flash community for over four years, supporting the community with tutorials, source files, moderating the Flashkit forums, and running his own Flash resource Web site, FlashGuru's MX 101. Guy was one of two developers who created the ever popular, award winning zoom interface for Relevare and now runs his own company, FlashGuru LTD, which builds Flash Games & Applications for clients such as Comic Relief, Egg and Channel 4.



 
 
Newsletter Archive | Article Archive | Submit Article | Advertising Information | About Us | Contact | Site Map

FlashNewz is an iEntry.com publication
© 1998-2009 iEntry Inc. All Rights Reserved Privacy Policy Legal