2

Using Javascript and regular expression, given:

stringHTML = "bla bla bla <img src='img1.png' /> bla bla bla 
<img src='img2.png' /> bla bla bla <img src='img3.png' />";

How do you remove

<img src='img1.png' />

the first img tag from stringHTML

ardiwine
  • 33
  • 1
  • 4

2 Answers2

4

Something like this would work:

var output = stringHTML.replace(/<img src='img1.png' \/>/, '');

This will find only the exact substring you've specified (a literal <img src='img1.png' />) and replace it with an empty string. Note that the forward slash needs to be escaped in the pattern because JavaScript uses forward slashes to delimit regular expression literals.

To remove the first <img> tag from the input string, regardless of the path or other attributes, you can use this:

var output = stringHTML.replace(/<img.*?\/>/, ''); 

This will find a literal <img followed by zero or more of any character, non-greedily, followed by a literal />. Note that without the global switch (g) it will only replace the first occurance

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
3

JavaScript comes with wonderful DOM parsing capabilities build right in.

x = document.createElement("x");
x.innerHTML = stringHTML;

x.removeChild(x.querySelector("img"));

Note that querySelector("img") selects the first image. If you specifically need to select the image with src=img1.png you can use the attribute selector. If query selector is not available, you will have to loop over img tags acquired with getElementsByTagName.

http://jsfiddle.net/ZsqK5/

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • +1. The problem as posed is possible to do with regular expressions, but it's a messy path to go down. This way is easier, more extensible and more maintainable. – user1002973 Sep 20 '13 at 22:10