Our Flash tutorials provide you with step-by-step instructions on how to create beautiful Flash animations and integrate them into your website.  Home Flash & Swish Flash Tutorials Reduce a String
Your Ad Here

Reduce a String


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<numWords;++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...

image 1



Author's URL: Guy Watson
Thank you for voting.
Rate this Materials:
Bad 
1 2 3 4 5 Excellent
print this page subscribe to newsletter subscribe to rss

Internet & computing Flash is a vector-based moving graphics format created by Macromedia for the publication of animations on the World Wide Web. More Flash & Swish: Most Popular Materials | Fresh Materials | More Flash Tutorials at FlashPerfection.com

Add comments to "Reduce a String"

Only registered users can write comment

No comments yet...