我需要使用javascript使链接可点击,我认为regex是最简单的,更不用说最快的方法。我希望所有的链接是可点击的,而不是重写已经存在的可点击的链接。
Example: 
Here is a link to visit http://www.example.com/page Please take a look <a href="http://www.example.com/page">here</a>.
Becomes: Here is a link to visit <a href="http://www.example.com/page">http://www.example.com/page</a> Please take a look <a href="http://www.example.com/page">here</a>.
Another example: Here is a link to visit http://www.example.com/page Please take a look here: <a href="http://www.example.com/page">http://www.example.com/page</a>
Becomes: Here is a link to visit <a href="http://www.example.com/page">http://www.example.com/page</a> Please take a look here: <a href="http://www.example.com/page">http://www.example.com/page</a>
And finally: <p id="demo">http://example.com/
<br><a href="http://example.com/123">http://example.com/123</a>
<br><a href="http://Google.ca/">http://Google.ca/</a></p>发布于 2012-09-16 05:35:00
这应该能起到作用:
var pattern = new RegExp("[^\"'](http://[^ ]*)","g");
var newContent = yourString.replace(pattern," <a href=\"$1\">$1</a>");tace对评论的关注:
var pattern = new RegExp("([^\"'])(http://[^ ]*)","g");
var newContent = yourString.replace(pattern,"$1<a href=\"$2\">$2</a>");在评论之后又进行了一次编辑,前一条评论指出链接不在开头:
var pattern = new RegExp("([^\"']||^)(http://[^ ]*)","g");
var newContent = yourString.replace(pattern,"$1<a href=\"$2\">$2</a>");您可能已经看到过这种模式,在正则表达式中,()中的内容被赋值给一个返回参数$1和$2,在这种情况下,在replace语句中使用witch is来重建字符串。这里的模式可能需要进一步扩展,因为您遇到了该模式没有捕获到的其他异常,例如,将链接放在()中不会得到想要的结果。使用正则表达式的一个很好的站点是regextester.com
发布于 2012-09-16 18:46:34
var text = [
        "http://www.example.com/page address at the begining then a well formated a tag take a look <a href='http://www.example.com/page'>here</a>.",
        " text in front http://www.example.com/page Please take a look <a href='http://www.example.com/page'>here</a>.",
        "  http less with get vars www.example.com/page?foo=bar Please take a look  <a href='http://www.example.com/page'>here</a>.",
        '<p>http://example.com/<br /><a href="http://example.com/123">http://example.com/123</a><br /><a href="http://Google.ca/">http://Google.ca/</a></p>'
    ] ,
    reg = /([\s>]|^)((?:http:\/\/)?(?:[a-z][\w-]+)+(?:\.[\w-]+)*(?:\.[a-z]{2,3})(?:[^ <]+))(?=[\s<]|$)/g,
    output = '';
    for(var key in text){
        $('body').append(
        '<div>'+
          text[key]
                .replace(reg, '$1<a href="$2">$2</a>')
                .replace(/(href=['"])(?!http:\/\/)/g, '$1http://')+
        '</pre>'
        );
    }可以在浏览器/Firebug控制台中测试。
应该进行更多的测试,以找到最受信任的极端分隔符/标记
https://stackoverflow.com/questions/12440232
复制相似问题