我要做的是,它编写一个javascript函数,让它加载文本,它将查找以.jpg.jpeg.gif.png等结尾的url,然后用嵌入图像的代码替换它们。因此,例如,一个文本如下:
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>");
}

最佳答案

好吧,您只需要将替换为<a>标记的标记更改为<img>。并添加一个regexp模式来检查.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

07-24 20:52