1

In an AIR app, I am loading a bunch of arbitrary text via JSON, loading it into an object, and displaying it via a custom renderer. I would like to have urls be clickable. So I'm sure that this is possible via some crazy regex thing (as I found for php here), but, Flex being flex, I'm astonished that there isn't some builtin functionality for this that I'm just not finding, or, failing that, a library that someone has created to do just this.

(I'm equally astonished that this question hasn't been asked here before. I anticipate being flamed with the link to that)

Failing that, anyone want to help with some crazy regex? ;>

Thanks in advance!

Community
  • 1
  • 1

2 Answers2

3

You could replace the URLs in your text for actual links using the following regex:

str = str.replace(/((https?|ftp|telnet|file):((\/\/)|(\\\\))+[\w\d:#@%\/;$()~_?\+-=\\\.&]*)/g, "<u><a href='$1'>$1</a></u>");

Then set the htmlText on a Label or Text component and listen for it's link event:

<mx:Text htmlText="{str}" link="linkHandler(event)"/>

Then open the URL on the handler:

public function linkHandler(event:TextEvent):void {
    navigateToURL(new URLRequest(event.text), '_blank');
}

Except for that regex, I haven't tested this code, but it should work. Also, this could be of some help to you.

leolobato
  • 2,359
  • 3
  • 32
  • 51
  • Hey, thanks. I put down this project for a minute so didn't come back to this tab to thank you in a timely fashion. Will try that and see how it goes. Thank you for comprehending crazy regex for me! –  Aug 30 '09 at 00:28
  • That was actually a problem I had in my code as well and I fixed it this way, so no problem! :) – leolobato Aug 30 '09 at 21:45
2

I would like to add that the following RegEx could be much more useful for validating an URL:

/(((f|ht){1}tp:\/)[-a-zA-Z0-9@:%_\+.~#?&\/=]+)/g

Kev
  • 118,037
  • 53
  • 300
  • 385
  • Wonderful. Could you explain what makes this regex preferable over the other? (I don't challenge it, I'm just curious. =) One thing I don't understand is why that {1} is necessary. Isn't "one and only one match" the default? – PEZ Jan 29 '11 at 09:02