使用正则表达式和JavaScript来使链接可点击但不会覆盖预先存在的链接?

时间:2012-09-15 19:09:49

标签: javascript regex hyperlink clickable

我需要使用javascript制作可点击链接,我认为正则表达式是最简单的,不提速度最快。我希望所有链接都是可点击的,并且不要重写现有的已经可点击的链接。

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>

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

var pattern = new RegExp("[^\"'](http://[^ ]*)","g");
var newContent = yourString.replace(pattern," <a href=\"$1\">$1</a>");

注意评论:

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>");

你可能已经看过模式了,在正则表达式中,inside()被赋予返回参数$ 1和$ 2,在这种情况下,在replace语句中使用了witch来重建字符串..这里的模式必须可能会进一步扩展,因为您遇到了其他未被模式捕获的异常,例如将链接放在()内部将无法获得所需的结果。使用正则表达式的好网站是regextester.com

答案 1 :(得分:0)

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控制台中测试。

应该进行更多测试以找到最值得信赖的极端分隔符/标记