【发布时间】:2011-11-25 11:08:52
【问题描述】:
我之前在 Flash 中编写过这个功能,没有问题;但是,我现在正在尝试使用 JavaScript 来实现,但遇到了一些困难。
使用正则表达式,我试图搜索一个字符串,寻找任何类似于链接的东西......例如http://www.google.com 或http://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/ 之后的任何内容都被忽略。因此链接不正确...
即使我发布了这个问题,Stack Overflow 界面也会提取我的文本并使用适当的链接标签将其呈现出来......我需要这样做。
欢迎提出任何建议。
-- 更新:
对不起,让我扩展一下。我不仅在寻找 http://,它还需要检测和包装以“https://”开头和/或仅以“www”开头的链接
【问题讨论】:
标签: javascript regex hyperlink textfield