我正在尝试编写一个简单的javascript函数来从文本中提取img urls。
我几乎得到它的工作,但我有一个params的问题我怎么能删除它们并返回完整的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;
}
答案 0 :(得分:1)
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 + "' />";
});
}