views:

430

answers:

3

Hello,

I am using a regular expression to find links in a generic string and highlight that text(underline, a href, anything).

Here's what I have so far:

var linkRegEx:RegExp = new RegExp("(https?://)?(www\\.)?([a-zA-Z0-9_%]*)\\b\\.[a-z]{2,4}(\\.[a-z]{2})?((/[a-zA-Z0-9_%]*)+)?(\\.[a-z]*)?(:\\d{1,5})?","g");
var link:String = 'generic links: www.google.com http://www.yahoo.com  stackoverflow.com';
link = addLinks(linkRegEx,link);
textField.htmlText = link;//textField is a TextField I have on stage

function addLinks(pattern:RegExp,text:String):String{
    while((pattern.test(text))!=false){
     text=text.replace(pattern, "<u>link</u>");
    }
    return text;
}

I get all the text replaced with "link". I'd like to have the same text that was matching the expresion instead of "link". I tried

text=text.replace(pattern, "<u>"+linkRegEx.exec(text)[0]+"</u>");

but I ran into trouble. I don't think I fully understand how regex and the replace method work.

A: 

I read here that in AS3 you have a replace function where you can pass a callback performing custom manipulation. This looks even more flexible than using standard regex capture groups.

AndreaG
A: 

If you just need to underline all the links in your textfield, the propper way to do it should be using StyleSheet... try with something like this:

var style:StyleSheet = new StyleSheet();
style.setStyle("a", {textDecoration:"underline"});
tf.styleSheet=style;
tf.htmlText="hello <a href='#test'>world</a>";
Cay
Thank you for the tip. You are right about doing the propper thing, but what is more important than the underline is having the a href. In you example: "tf.htmlText="hello <a href='#test'>world</a>";" I want #test to be replaced with the pattern matched string (e.g. www.google.com, http://www.yahoo.com, stackoverflow.com, etc. )
George Profenza
+2  A: 

Ok, I've read the documentation for the replace() method.

There are two key things:

  1. You can use $& to get the matched substring. A lot of handy and weird looking symbols there.
  2. Use a second string when replacing, otherwise you end up in an endless loops and tiny black wholes keep spawning every now and then.

Here's how the correct version of the function looks:

function addLinks(pattern:RegExp,text:String):String{
    var result = '';
    while(pattern.test(text)) result = text.replace(pattern, "<font color=\"#0000dd\"><a href=\"$&\">$&</a></font>");
    if(result == '') result+= text;//if there was nothing to replace
    return result;
}

As Cay mentioned, a stylesheet is more apropiate for styling. Thanks for the input.

George Profenza