Reputation: 4290
I am trying to write a simple javascript function to pull just img urls out of text.
i have nearly got it working but i am having a issue with params how can i remove them and also returning the full img url, could someone help not the best at regexs
document.write(getImagesInText("Whether the view should hidden from (i.e., ignored by) the accessibility service. http://jsfiddle.net/ http://thickbox.net/images/plant4.jpg afhttp://thickbox.net/images/plant4.jpg?4t34t34t"));
function getImagesInText(text){
var html = text;
var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)+\.(?:jpg|jpeg|gif|png)/gi;
return html.replace(urlRegex, '<img src="$1" width="48" height="48"/>');
}
view the example here.
http://jsfiddle.net/7dJCm/1/
UPDATE
function getImagesInText( s ) {
var html = s;
var imgregex = /((http(s)?|ftp):\/\/[\S]*(\.jpg|.jpeg|\.gif|.png)[\S]*)/gi;
var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
html = html.replace(/(\.jpg|\.jpeg|\.gif|\.png)/gi, function( ext ) { return ext + " "; });
html = html.replace(/(http|https)/gi, function( ext ) { return " " + ext; });
html = html.replace(urlRegex, function( path ) {
if(path.match(/jpg|png|gif|jpeg/g)){
return "<img width='48' height='48' src='" + path + "' />";
}else{
return "<a href='" + path + "'>" + path + "</a>";
}
});
return html;
}
Upvotes: 1
Views: 280
Reputation: 47099
var s = "Whether the view should hidden from (i.e., ignored by) the accessibility service. http://jsfiddle.net/ http://thickbox.net/images/plant4.jpg afhttp://thickbox.net/images/plant4.jpg?4t34t34t";
console.log( getImagesInText(s) ) // "Whether the view should hidden from (i.e., ignored by) the accessibility service. http://jsfiddle.net/ <img src='http://thickbox.net/images/plant4.jpg' /> af<img src='http://thickbox.net/images/plant4.jpg?4t34t34t' />"
function getImagesInText( s ) {
var regex = /((http(s)?|ftp):\/\/[\S]*(\.jpg|\.jpeg|\.gif|\.png)[\S]*)/gi;
return s.replace(regex, function( path ) {
return "<img src='" + path + "' />";
});
}
Upvotes: 1