最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Need Regular expression javascript to get all images - Stack Overflow

programmeradmin1浏览0评论

I have string that contains html . The html has several img tags in it . I want to find all the img tags and have some kind of collection so that i can replace them with my code.

Does anybody has any idea.

I want it in Javascript

I have string that contains html . The html has several img tags in it . I want to find all the img tags and have some kind of collection so that i can replace them with my code.

Does anybody has any idea.

I want it in Javascript

Share Improve this question edited Oct 13, 2011 at 12:29 Chief asked Oct 13, 2011 at 12:07 ChiefChief 9141 gold badge9 silver badges26 bronze badges 5
  • 3 Regex is not the tool for this. jQuery would be able to do it out of the box - any chance of using that? – Pekka Commented Oct 13, 2011 at 12:10
  • if i dont get collection then can i replace all of them with my predefined code – Chief Commented Oct 13, 2011 at 12:13
  • Yup, that is possible as well. – Pekka Commented Oct 13, 2011 at 12:14
  • What do you mean by collection – Petah Commented Oct 13, 2011 at 12:14
  • a collection means list or possibly all the img ones in a array – Chief Commented Oct 13, 2011 at 12:17
Add a ment  | 

3 Answers 3

Reset to default 5
var html_str = '...some images and other markup...';

var temp = document.createElement( 'div' );
temp.innerHTML = html_str;

var images = temp.getElementsByTagName( 'img' );

...then loop over the images...

for( var i = 0; i < images.length; i++ ) {
    images[ i ].className = "my_class";
}

What you actually need to do may change how your loop runs, but the above just adds a class, so it is just a normal for loop.

Note that at this point you're dealing with DOM elements, not markup. These elements can be added directly to the DOM.

If you used jQuery you could do something like:

var html = '<div><img src="bla" /></div>';
$(html).find('img');

If you want to replace all images you would do:

var html = '<div><img src="bla" /></div>';
$(html).find('img').replaceWith('<div>Image was here</div>');

This is regex pattern to take all image tag:

var pattern = /\<img .+?\/\>/ig;

UPDATE: sample is here http://jsbin./oxafab/edit#source

发布评论

评论列表(0)

  1. 暂无评论