检测图像链接并嵌入它们

时间:2014-01-05 07:31:31

标签: javascript jquery html

我要做的是,它编写了一个javascript函数,您可以在其中添加大量文本,并查找以.jpg.jpeg.gif结尾的网址,.png等,然后将其替换为嵌入图像的代码。因此,例如,文字如:

  

Bacon ipsum dolor sit amet shank pork loin ground round beef meatloaf landjaeger tongue chicken strip steak short loin jowl pork chop meatball. Doner shank sausage, tri-tip jerky frankfurter tongue. Venison meatloaf kielbasa, hamburger ball tip tongue beef boudin shoulder spare ribs landjaeger short loin shank. http://1.bp.blogspot.com/-jzdnfSEhmEQ/UDvjPnb-Z0I/AAAAAAAACN4/jTQMom9Fr1c/s320/improvKitchen_howToCookBacon_00.jpg Ham hock ribeye swine sirloin tri-tip kielbasa turkey. Venison strip steak landjaeger corned beef ribeye, pig t-bone pancetta fatback drumstick short ribs sausage pork swine turkey. Jerky chuck bacon turducken doner salami andouille short ribs pork kielbasa drumstick pork chop.

会返回

  

Bacon ipsum dolor sit amet shank pork loin ground round beef meatloaf landjaeger tongue chicken strip steak short loin jowl pork chop meatball. Doner shank sausage, tri-tip jerky frankfurter tongue. Venison meatloaf kielbasa, hamburger ball tip tongue beef boudin shoulder spare ribs landjaeger short loin shank. <img src="http://1.bp.blogspot.com/-jzdnfSEhmEQ/UDvjPnb-Z0I/AAAAAAAACN4/jTQMom9Fr1c/s320/improvKitchen_howToCookBacon_00.jpg" /> Ham hock ribeye swine sirloin tri-tip kielbasa turkey. Venison strip steak landjaeger corned beef ribeye, pig t-bone pancetta fatback drumstick short ribs sausage pork swine turkey. Jerky chuck bacon turducken doner salami andouille short ribs pork kielbasa drumstick pork chop.


我已经有了一个链接功能,如果有任何帮助我在另一个SO帖子中找到:

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1' target='_blank'>$1</a>"); 
}

1 个答案:

答案 0 :(得分:3)

您只需要将<a>代码标记替换为<img>即可。并添加正则表达式模式以检查.jpg, .jpeg, .gif, .png

function replaceURLWithImage(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])+\.(?:jpe?g|gif|png)/ig;
    return text.replace(exp,"<img src='$1'/>"); 
}

请参阅此jsfiddle demo