1

简单地说,我想解析 URL 链接并使用 jQuery、RegEx 添加 html 引用。

源 HTML 是:

<div id="test"> my favorite search engines are http://www.google.com 
    and http://stackoverflow.com Do you agree? </div>

我当前的脚本是:

var exp = /(^|[^'">])((ftp|http|https):\/\/(\S+))(\b|$)/gi;
$('#test').html($('#test').html().replace(exp,
    "&nbsp;<a href='$2' target='_blank'><img src='go.gif'/></a>"));
});

其结果如下:

<div id="test"> my favorite search engines are 
<a href="http://www.google.com" target='_blank'>
<img src='go.gif'/></a> and
<a href="http://stackoverflow.com" target='_blank'>
<img src='go.gif'/></a>
Do you agree? </div>

我知道这个脚本只是替换并且不能保留它的来源。我想在“img 标签”之后添加它的原始 URL。任何人都有想法得到以下结果?

<div id="test"> my favorite search engines are 
<a href="http://www.google.com" target='_blank'>
<img src='go.gif'/>http://www.google.com</a> and
<a href="http://stackoverflow.com" target='_blank'>
<img src='go.gif'/>http://stackoverflow.com</a>
Do you agree? </div>

提前感谢您的评论。

4

3 回答 3

1

This is the solution (you can test the regular expression here: http://regexr.com/)

var test = $('#test'),
    txt = test.html(),
    pattern = /((?:http|ftp|https):\/\/[\w\-_]+(?:\.[\w\-_]+)+(?:[\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)/gi;

test.html(txt.replace(pattern, '<a href="$1" target="_blank"><img src="go.gif"/>$1</a>'));

You can add some css:

#test a img { margin-right: 5px; }
于 2013-06-27T04:06:23.697 回答
0

像这样的东西:

var urlRE = /(^|[^'">])((ftp|http|https):\/\/(\S+))(\b|$)/gi;
var $test = $('#test');
var text = $test.text();

text = text.replace(urlRE, "<a href=\"$&\">$&</a>");

$test.html(text);

jsFiddle

于 2013-06-27T03:57:51.993 回答
0
于 2013-06-27T03:59:29.423 回答