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
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
Share Improve this question asked Sep 20, 2013 at 21:49 ardiwineardiwine 331 silver badge4 bronze badges 2- Obligatory – tckmn Commented Sep 20, 2013 at 21:50
-
2
With
String.replace(/<img[^>]+>/, '')
. Withoutg
flag, there'll be only a single replacement. – raina77ow Commented Sep 20, 2013 at 21:51
2 Answers
Reset to default 4Something 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
JavaScript es 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/ZsqK5/