How to replace all links in text with regex in as3?

Possible duplicate:
How to link text using ActionScript 3

I use a regex to search for links in a common line and highlight this text (underline, href, whatever).

Here is what I still have:

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 by the link. I would like to have the same text that matches the expression instead of "link". I tried

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

but I ran into a problem. I don’t think I fully understand how the regex and replacement method work.

0
source share
3 answers

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

:

  • $&, . .
  • , , .

:

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;
}

, . .

UPDATE

RegEx, , , #. :

function addAnchors(text:String):String{
    var result:String = '';
    var pattern:RegExp = /(?<!\S)(((f|ht){1}tp[s]?:\/\/|(?<!\S)www\.)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/g;
    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;
}
+2

, AS3 replace, , . , .

+1

, StyleSheet. - :

var style:StyleSheet = new StyleSheet();
style.setStyle("a", {textDecoration:"underline"});
tf.styleSheet=style;
tf.htmlText="hello <a href='#test'>world</a>";
+1

Source: https://habr.com/ru/post/1751035/


All Articles