将包含突出显示的链接转换为<a> tags

时间:2017-02-20 00:13:41

标签: javascript

At the moment, I can convert this text:

Hello this is a link: http://foo.bar cheers! 

Into Hello this is a link: <a href="http://foo.bar">http://foo.bar</a> cheers!

However; I use ElasticSearch to search and sometimes it highlights words within the URLs themselves; and wraps them in <em> tags like this:

Hello this is a link: http://<em>foo</em>.bar cheers! 

Which breaks my regex and doesn't wrap the URL in an <a> tag properly.

Here's how I do this at the moment:

  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;

  text = text.replace(exp, function($1){
    return "<a href='"+$1+"'>"+$1+"</a>";
  }); 

Which results in a broken tag:

enter image description here

P.S。我想继续突出显示 - 我知道我可以删除em代码然后转换链接。

1 个答案:

答案 0 :(得分:1)

这对你有用吗?

var exp = /(\b(https?|ftp|file):\/\/[^\s]+)/ig;
var text = text.replace(exp, function($1){
    var s = $1;
    s = s.replace(/<\s*\/?\s*em\s*>/ig,'');
    return '<a href="'+s+'">'+$1+'</a>';
});