Posted on April 25, 2007 by Lanny McNieTo continue the Extension goodness, here is an uber-handy AS3 class that we built the second we had access to AS3. VI. AS3 String UtilsWith the advent of regex in Actionscript, string methods become easier, and in some cases a lot faster. It also gave us a good exercise in AS3. This class is found in the com.chewtinfoil.utils package. Exampleimport com.chewtinfoil.utils.StringUtils; var str:String = "This is some <b>Text</b> that contains <i>HTML Characters</i>."; var newStr:String = StringUtils.stripTags(str); trace(newStr); // This is some Text that contains HTML Characters. APIAll these static methods are documented in the class using ASDoc-style comments.
Follow @gskinner on Twitter for more news and views on interactive media.
|
|
|
47 Comments
Thanks Lanny.
Also thanks to Stacey for "announcing" it at FITC this year :)
There are more utility classes in the works, including Date & Array Utils.. we'll try and keep you all posted.
Posted by: Ryan Matsikas on Apr 25, 2007 11:58am URL: http://gskinner.com
Thanks Grant. I was at Stacey's session and I thought it sounded pretty good.
-tim.
Posted by: tim on Apr 25, 2007 12:06pm
Bugs! I think you need to escape more things in more places, because you're often using passed-in Strings to directly construct a RegExp.
For example:
var price :String = "$40";
trace(StringUtils.beginsWith(price, "$"));
Posted by: Ray Greenwell on Apr 25, 2007 12:53pm
Thanks Ryan.
Posted by: Randy Troppmann on Apr 25, 2007 3:22pm URL: http://www.spintechnologies.ca/flashblog
@Ray: Fixed that and updated the zip, lemme know if you find others.
@Randy: No Problemo, hope you can put them to good use.
Posted by: Ryan Matsikas on Apr 25, 2007 4:08pm URL: http://gskinner.com
I had created a Number utils class a while back and was nearing the point where a String utils class was necessary. This solves it--thanks!
Posted by: Nate Chatellier on Apr 25, 2007 6:24pm URL: http://blog.natejc.com
The capitalize method doesn't work as I expected. That is, when I pass true for the second parameter I don't get all words capitalized.
Posted by: Phillip Kerman on Apr 25, 2007 7:16pm
@Phillip: All fixed, looks like some of the AS3 API's I used changed from when I originally put this class together.
Get the updated zip everyone!
Posted by: Ryan Matsikas on Apr 26, 2007 10:42am URL: http://gskinner.com
AKA the gString class. :)
Posted by: Randy Troppmann on Apr 30, 2007 3:20pm URL: http://www.spintechnologies.ca/flashblog
I just downloaded the class and ran a compile. I got the following errors:
Warning: 3596: Duplicate variable definition. @ line 279
and
Warning: 1012: Variables of type uint cannot be undefined. The value undefined will be type coerced to uint before comparison. @ line 642
These don't break my application but I thought I would bring it to your attention. By the way, great class thanks for posting it!
Posted by: Jesse Freeman on May 2, 2007 8:48am URL: http://www.flashbum.com
awesome, thanks for sharing - lookin forward to the array and date utils!
Posted by: taber on May 13, 2007 1:54am
I think you want to revise StringUtils.endsWith():
p_string.indexOf(p_end) ...
to:
p_string.lastIndexOf(p_end)
otherwise, it will return false in cases where it finds the suffix char/s index before the actual suffix itself... for example:
trace(StringUtils.endsWith("class", "s"))
returns false when it should return true, because it is finding the first "s" and that does not equal the intended comparator position...
Thanks for the very helpful utils though!
Posted by: alinear on Jun 11, 2007 8:54pm URL: http://www.alinear.net
This is a great class. I do get Compiler Errors though, however, it still compiles and runs fine. Here are errors:
Line 279: Warning 3596 Duplicate variable definition.
Line 642: Warning 1012 Variables of type uint cannot be undefined. The value undefined will be type coerced to uint before comparison.
Posted by: dzedward on Jan 7, 2008 10:04am URL: http://www.flashgods.org/
@dzedward
The errors you are describing are simply syntax warnings, and as such have no effect on the performance or behaviour of this class.
We actually created this class during the "Flash 8 AS3 Preview" days, before the language was complete, and warnings didn't exist. I will endeavor to post a new version with those warnings removed, as I know how annoying they can be when working in a larger project.
Thanks!
Posted by: Lanny McNie on Jan 7, 2008 10:15am URL: http://gskinner.com
Thanks, that sounds great. Yea, they can get annoying hehe
Posted by: dzedward on Jan 8, 2008 9:20am URL: http://www.flashgods.org/
What if I want to find a word in a string?
Posted by: theranch on Mar 3, 2008 2:37pm URL: http://www.thespikeranch.com
i tried to use this extension but recently found one i like better on peakstudios.com it creates the code for you and uploads all of the classes on instalation.
Posted by: Jeremy on Apr 21, 2008 10:00am URL: http://www.skitripusa.com
Hi Grant - great set of methods there, thanks for sharing them!
Just one thing that I'd like to see changed in the truncate method - if you give it a long string which equates to just one word, it truncates down to nothing.
I think it should show all the chars it can, and break the word off with the ... trailing.
Posted by: Dan on Jun 16, 2008 10:52am URL: http://www.danwashere.com
thanks alot !! It's very what I want!!! ^^
Have a good day~!
Posted by: hyunho lee on Nov 10, 2008 7:53pm
thanks. great work!
Posted by: koala on Nov 13, 2008 7:47am
Thanks a lot for the useful extension. It works perfectly!
Posted by: Luca on Jan 30, 2009 8:04am
Thank-you for releasing these functions!
One thing you need to do: add "|\|" to the end of the regex in escapePattern. Thanks again.
Posted by: Dallan Quass on Feb 7, 2009 2:30pm URL: http://www.werelate.org/wiki/User:Dallan
This is a great tool, thanks!
Posted by: lars // dk on Feb 13, 2009 7:42am
Very useful tools, thank you for hard work!
Posted by: en3rgizer on Mar 18, 2009 4:23am URL: http://en3rgizer.blogspot.com
It works like a charm!
Posted by: Jk_ on Apr 28, 2009 2:26am
Great, thanks for these rocking Utilz.
I did find a small typo with 'removeExtraWhiteSpace', it should be 'removeExtraWhitespace'. To many humps.
Posted by: Dano Manion on Jul 8, 2009 1:54pm URL: http://www.danomanion.com
I found your class by accident, while searching for a trim method in Actionscript (could've used String.replace() but I was hoping there was something built-in :) ). So I found your class and I thought it might be useful, but didn't really feel like including an entire new class coded by someone else into my project (there's something about 'I coded this entirely!' logic I like), but since the class looked like a library I included it in the project (and use the remoteExtraWhitespace() function).
I then had a need for a function that would return all characters after the last occurrence of a certain character. I implemented this using regex initially and started having a bunch of regex's all over the place. Overall, I don't think there is anything wrong with using regexs, but it was so convenient to use your functions! beforeFirst(), afterFirst(), beforeLast(), afterLast() - I felt so spoiled! An added benefit you realize you get only after using a few functions - the code becomes more readable! Regexps are useful, but it takes a few seconds to figure out what is the purpose of that expression (I generally write a comment for that, in case I forget ;) ). And certainly, writing a comment is a solution, but having the code tell you what it's doing is so much more elegant.
Thank you for coding this class and making it free. It made my life a tad easier!
On another note, I do have 2 requests related to it:
1. There were 2 trace() commands left in the file somewhere. I deleted them, but you might want to remove them too.
2. I'm not sure what the purpose of the padRight() function was initially, but I tried to use it to display a list of commands and their descriptions in 2 columns, using a textfield. They all padded correctly, but were misaligned, because (I suspect) the font is not fixed-width, so some characters are wider than the other. I would love to see another function in there that would add output text in columns and would arrange the columns properly, or have the function add as many spaces as necessary to accommodate a certain column width.
Overall, great job and thanks again for this useful class!
Posted by: Victor on Aug 14, 2009 4:20pm
Hi,
is it possible to find the index(startIndex & endIndex) of specified word from the input text box... for example
input text box contains : "the world is not enoug", here the word enough spelling is not correct, will compare the text with some dictionary and need to highlight the wrong words, in this case i need to highlight "enoug", to highlight the word i need to know the startIndex and endIndex of the word... so how to find out the indexs... any help will be highly appreciated..... Thanks in advance....
Posted by: PruthviRaj on Sep 1, 2009 6:49am
Thanks for this v.handy.
Posted by: Josh Noble on Sep 3, 2009 7:56am URL: http://www.visualdialects.co.uk
thanks for your utils. i have a new function that i often use in conjunction with swfaddress:
i created a toSEO function to generate a proper url out of something like "Gratis Fürsorge für alle!". the result is "gratis-fuersorge-fuer-alle".
are you interested in adding it to your utils class?
Posted by: lauritz on Sep 25, 2009 11:50am
Thanks for this free actionscript resource. Really helps alot.
Posted by: Newbie on Sep 28, 2009 8:36am URL: http://portaltoafrica.com
Awesome class!
@Victor
A simple way to do a replace is to just copy the remove method and modify it slightly.
Here is what I ended up changing it to:
http://pastebin.com/f175fd99d
public static function replace(p_string:String, p_remove:String,p_replace:String = '', p_caseSensitive:Boolean = true):String {
if (p_string == null) { return ''; }
var rem:String = escapePattern(p_remove);
var flags:String = (!p_caseSensitive) ? 'ig' : 'g';
return p_string.replace(new RegExp(rem, flags), p_replace);
}
Posted by: Charlie Schulze on Dec 16, 2009 7:23pm URL: http://www.papervision2.com
This is Brilliant, Many thanks!
Posted by: Philip on Dec 28, 2009 11:32am URL: http://www.how-to-code.com
Is there a way to use the striptags function but with another parameter. For example to strip everything but the tags?? How would you write a regExp to suit this?
Posted by: Josh on Jan 9, 2010 8:57am URL: http://www.iamsecond.com
"There are more utility classes in the works, including Date & Array Utils.. we'll try and keep you all posted."
Did you ever get around to posting these? If so, can you reply with a link to them?
Many thanks and keep up the great work.
Cheers,
Adrian
Posted by: Adrian Parr on Feb 7, 2010 4:03am URL: http://www.adrianparr.com
Thx, this is a handy usefull class. I found it by accedint as well while I was looking for a trim function that I hoped to be built-in in the string class
Cheers,
ASM
Posted by: ASM on Feb 7, 2010 8:08pm
For block(), is there a simple way to pass multiple punctuations as the delimeter to handle question marks and exclamation points in addition to periods?
Posted by: robodevil on Feb 9, 2010 9:30am
There is a bug in the removeExtraWhitespace function.
Change:
return str.replace(/\s+/g, ' ');
To:
return str.replace(/\s+/g, '');
Basically the original replaces white space with... white space lol. If you remove the space in between it will work correctly!
Posted by: Dan on Jul 8, 2010 8:11pm
Really useful class this! I deal a lot with htmlText for CMS's - the contentOf function allows me to count any duplicate words but is there any way to write a similar expression that returns an array of the positions (within an htmlText as String() ) of a particular word?
This would be bloody helpful - any hints or pointers would be greatly appreciated!
Posted by: Wayne on Aug 5, 2010 7:22am
Wayne,
Thanks for the kind words, glad you are getting use out of the class.
To accomplish what you want you'd need todo a bit more work and iterate over the string searching for your input. Look at the RegExp.exec() docs.
Simple example:
var str:String = 'A sentance with repeating chars';
var r:RegExp = new RegExp('a', 'ig'); // find 'a', ignore case..
var m:Object = r.exec(str); // look for first match
while (m != null) {
trace(m, m.index);
m = r.exec(str);
}
Returns..
A 0
a 6
a 20
a 28
Hope that helps.
Posted by: Ryan Matsikas on Aug 5, 2010 11:13am URL: http://gskinner.com
Fantastic!
You should see some of the (cpu intensive) loops of if's and while's I've been trying to emulate the same result.
Can't thank you enough sir!
Posted by: Wayne on Aug 6, 2010 7:05am
Is there a way to include accented char in the function capitalize ?
like : marie-élaine would become Marie-Élaine
tx !
Posted by: jim on Oct 20, 2010 1:29pm
this is awesome. saved me a lot of headache. Big Ups!
Posted by: Pav on Apr 25, 2011 7:14pm
OMG!!!!!!!!!!!!! I SO OWE YOU BEER!!!!!!!!!!!!!!!!!!!!!!!
Posted by: Mike Kerr on May 26, 2011 5:35pm URL: http://www.reactiongears.com
Does this method actually work for anyone?
removeExtraWhitespace()
I get a next infinite loop from this code:
while( StringUtils.contains( myString , ' ' ))
myString = StringUtils.removeExtraWhitespace( myString );
Posted by: Hays on Jun 1, 2011 2:22pm
Ahh... I see the fix a couple comments up. To bad this file isn't in a repo.
Posted by: Hays on Jun 1, 2011 2:29pm
how about truncate a String in a Textfield by restricting it to a number of lines?
Posted by: isaac on Nov 9, 2011 8:53am URL: http://www.zacalves.com