读书人

提取HTML代码中的图片URL地址lt;img标

发布时间: 2012-05-29 12:16:00 作者: rapoo

提取HTML代码中的图片URL地址,<img标签内属性排列不规则情况,正则怎么写
如题,提取HTML代码中的图片URL地址
<script language="javascript">
var picFiles="";
function getimgsrc(htmlstr){
picFiles="";
var re=/<(?:img|embed|script)(?:\s+\w+\s*=\s*[^\s>]+)*\s+src(?:\s)*=(?:\s)*([^\s>]*)/gim
while(re.exec(htmlstr) != null) {
picFiles=picFiles+((RegExp.$1).replace(/["']/g,""))+"|";
}
}

function selectPics()
{
var htmlStr="<P align=center><FONT size=3><IMG src='/include/eWebEditor/UploadFile/200941092128708.jpg' width=636 border=0>ddd<IMG style='WIDTH: 294px; HEIGHT: 245px' src=/include/eWebEditor/UploadFile/20094109234712.jpg' width=441 height=341 border=0></P>";
getimgsrc(htmlStr);
alert(picFiles);
if(picFiles=="")
{
alert("对不起,您的详细内容中没有图片可供选择!");
return;
}
}
</script>


问题出现在,第一个img的URL取得到,但是第2个IMG就取不到了,<img中src前多了个:style='WIDTH: 294px; HEIGHT: 245px'请问该如何取消这些src前的所有字符?请教高手,因为有可能还有其他如width=441 height=341 也排在前边,有可能就无法获取了

[解决办法]
为什么要用正规? 用document.getElementsByTagName('img') 最简便。
[解决办法]
按你给的字符可以

HTML code
<script language="javascript"> function  getimgsrc(htmlstr){    var reg=/<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;    var arr = [];    while(tem=reg.exec(htmlstr)){        arr.push(tem[2]);    }    return arr;}var htmlStr=" <P align=center> <FONT size=3> <IMG src='/include/eWebEditor/UploadFile/200941092128708.jpg' width=636 border=0>ddd <IMG style='WIDTH: 294px; HEIGHT: 245px' src=/include/eWebEditor/UploadFile/20094109234712.jpg' width=441 height=341 border=0> </P>"; var imgs=getimgsrc(htmlStr); alert(imgs.join('\n'));</script> 

读书人网 >JavaScript

热点推荐