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



我需要使用 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>
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 控制台中进行测试。

应进行更多测试以找到最受信任的极值分隔符/标记

这应该可以解决问题:

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

您可能已经看到了该模式,在这种情况下,在正则表达式中()内部的内容被分配给返回参数$1和$2,witch在replace 语句中使用以重建字符串。当您遇到模式未捕获的其他异常时,此处的模式可能必须进一步扩展,例如将链接放在 () 中不会给出所需的结果。一个使用正则表达式的好网站是 regextester.com

最新更新