Benedict Lewis
Benedict Lewis

Reputation: 2813

Detect image links and embed them

What I am trying to do, it write a javascript function where you give it a load of text, and it will look for URLs which end in .jpg, .jpeg, .gif, .png etc, and then replaces them with the code for an embedded image. So, for example, a text like:

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.

Would return

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.


I already have a function for links which I found in another SO post if that is of any help:

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>"); 
}

Upvotes: 2

Views: 176

Answers (1)

Mark S
Mark S

Reputation: 3799

Well you just need to change that replace to <a> tag markup to an <img>. And add a regexp pattern to check for .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'/>"); 
}

See this jsfiddle demo.

Upvotes: 3

Related Questions