views:

18

answers:

1

I am getting a string from Twitter into my Actionscript which is a unformatted string. I want to be able to extract any links and or any @replies from the string, then display it in htmlText.

So far I have this

var txt:String = "This is just some text http://www.thisisawebsite.com and some more text via @sumTwitter";

var twitterText:String = txt.slice(txt.indexOf("@"),txt.indexOf(" ",txt.indexOf("@")));

var urlText:String = txt.slice(txt.indexOf("http"),txt.indexOf(" ",txt.indexOf("http")));

var newURL:String = ""+urlText+"";

var arr:Array = txt.split(urlText);

var newString:String = arr[0] + newURL + arr[1];

var txtField:TextField = new TextField();
txtField.width = 500;
txtField.htmlText = newString;
addChild(txtField);

This is fine for extracting links, which finish with a space. But what if, like the @sumTwitter, it finishes at the end of the string. And also what if there are multiple links or @'s, is the best way to put it in a while loop?

+2  A: 

Regular expressions are the best option for what you want, I think.

Check Grant Skinner's RegExr. You could write and test your own RegExp there, which is very convenient. But you also can find a lot of useful ready-to-use regexps created by different users. Check out the "community" tab in the right panel. There, search by some meaningful keywords like "twitter" and "url" and you'll get a good number of options.

For example,

Grab urls:

http://regexr.com?2s5m4

Capture twitter usernames:

http://regexr.com?2s5m7

Juan Pablo Califano
nice, thanks JPC!
daidai