2011-09-26 70 views
1

我之前在Flash中没有写过这样的功能;不过,我现在试图用JavaScript来做,而且我遇到了一些困难。REGEX Str替换 - 查找链接文本并将它们链接起来

使用正则表达式,我试图冲刷一个字符串寻找类似链接的任何东西......例如http://www.google.comhttp://stacoverflow.com/question/ask;然后用适当的结果包装该结果::

<script type="text/javascript> 
var mystring = "I'm trying to make this link http://facebook.com/lenfontes active." 
/// REGEX that worked in Flash to grab ALL parts of the URL including after the .com... 

var http = /\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/gi; 

// preform the replace based on the Regex 
mystring = mystring.replace(http, function(){ 
    var link = arguments[0]; 
if (link.indexOf("http") == -1){ 
    link = "http://" + link;} 
    return "<a href='"+link+"'>"+arguments[0]+"</a>"; 
}); 

$('#results).html(mystring); 
</script> 

我遇到的问题:忽略com /后面的任何内容。因此,链接是不正确的...

即使我发布这个问题,堆栈溢出接口采取了我的文本,并与相应的链接标记呈现出来......我需要这样做。

欢迎任何建议。

- 更新:

对不起,让我扩大..我不是只想找的http://它需要检测和包装,与开始链接“https://开头”和/或刚开始“WWW”

回答

2

你的正则表达式不起作用,因为ECMA(JavaScript的)不支持POSIX字符类,所以[:punct:]忽略.com.