如何使用 ActionScript 3 链接文本 [英] How do I linkify text using ActionScript 3
问题描述
我有一个要链接的文本(识别 URL 并将它们转换为 HTML 链接).文本可以是多行的,并且可以包含多个 url,如下例所示.
I have a text that I want to linkify (identify URLs and convert them to HTML links). The text could be multi-line, and could contain multiple urls like the example below.
我当前的动作脚本代码如下
My current actionscript code looks like this
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private function init():void {
var str:String = "@stack the website for google is http://www.google.com and gmail is http://gmail.com";
//Alert.show(linkify(str),"Error");
txtStatus.htmlText = linkify(str);
}
private function linkify(texty:String):String {
//return texty.replace("/[A-Za-z]+://[A-Za-z0-9-_]+.[A-Za-z0-9-_:%&?/.=]+/g",function(m):String { return m.linkify(m);});
//return texty.replace(/[A-Za-z]+://[A-Za-z0-9-_]+.[A-Za-z0-9-_:%&?/.=]+/g, function(m):String {return m.linkify(m);}).replace(/(^|[^w])(@[dw-]+)/g, function(m2):String{return '@<a href="http://twitter.com/' + m2.substr(1) + '">' + m2.substr(1) + '</a>'; });
var pattern:RegExp = /[A-Za-z]+://[A-Za-z0-9-_]+.[A-Za-z0-9-_:%&?/.=]+/g;
var match:String = pattern.exec(texty);
return texty.replace(pattern,'<a href="' + match + '">' +
match + '</a>');
}
]]>
</mx:Script>
上述脚本的问题在于它识别出第一个匹配项并使用它.另外我如何为 @
做这件事?
The problem with the above script is that it recognizes the first match and uses that across. Also how do i do it for @
?
非常感谢任何帮助.
推荐答案
ooph ... 为什么现在每个人都使用正则表达式来完成超级简单的任务?此外,您忘记了,+"是 URL 的有效字符,可以替代空格,甚至是 可能会使用很多其他字符,因此您的模式甚至不会相应地匹配...
ooph ... why does everybody use regex these days, to accomplish super simple tasks? also, you forgot, that "+" is a valid character for URLs, as a replacement for space, and even an awful lot of other characters may be used, so your pattern would not even match accordingly ...
好吧,无论如何,看看 AS3 正则表达式元字符 ...这将大大提高您的表达式的可读性并且更加健壮......
well, anyway, have a look at AS3 regex metacharacters ... that'll GREATLY improve your expression's readability and is much more robust...
我真的会选择这样的:
var r:RegExp = /(?:http|https)://S*/g;
trace(str.replace(r, function (s:String,...rest):String {
return '<a href="' + s + '">' + s + '</a>'
} ));
但实际的重点是 global
标志...
but the actual point, was the global
flag ...
祝你好运... :)
问候
back2dos
这篇关于如何使用 ActionScript 3 链接文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!