0

我需要使用 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>
4

2 回答 2

0

This should do the trick:

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

To tace care of the comment:

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

One more edit after comment, the previous one asumed the link was not at the beginning:

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

You have probably seen the pattern already, in regular expressions what is inside () are asigned to a return parameter $1 and $2 in this case, witch is is used in the replace statement to rebuild the string.. The pattern here must probably be extended further as you come across other exceptions not catched by the pattern, for instance putting the link inside () would not give the desired result. A nice site to play with regular expressions is regextester.com

于 2012-09-15T21:35:00.087 回答
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 控制台中进行测试。

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

于 2012-09-16T10:46:34.197 回答