我正在尝试编写一个简单的 javascript 函数来从文本中提取 img url。
我几乎让它工作了,但我遇到了参数问题,我该如何删除它们并返回完整的 img url,有人可以帮助不是最擅长正则表达式的人吗
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"/>');
}
在此处查看示例。
http://jsfiddle.net/7dJCm/1/
更新
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;
}