【问题标题】:REGEX Str Replace- finding link text and making them linksREGEX Str Replace - 查找链接文本并使其成为链接
【发布时间】:2011-11-25 11:08:52
【问题描述】:

我之前在 Flash 中编写过这个功能,没有问题;但是,我现在正在尝试使用 JavaScript 来实现,但遇到了一些困难。

使用正则表达式,我试图搜索一个字符串,寻找任何类似于链接的东西......例如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/ 之后的任何内容都被忽略。因此链接不正确...

即使我发布了这个问题,Stack Overflow 界面也会提取我的文本并使用适当的链接标签将其呈现出来......我需要这样做。

欢迎提出任何建议。

-- 更新:

对不起,让我扩展一下。我不仅在寻找 http://,它还需要检测和包装以“https://”开头和/或仅以“www”开头的链接

【问题讨论】:

    标签: javascript regex hyperlink textfield


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-10-03
      • 2011-09-19
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 2012-12-27
      相关资源
      最近更新 更多