I have a string that contains HTML image elements that is stored in a var.
I want to remove the image elements from the string.
I have tried: var content =
Does this work for you?:
var content = content.replace(/<img[^>]*>/g, '')
You could load the text as a DOM element, then use jQuery to find all images and remove them. I generally try to treat XML (html in this case) as XML and not try to parse through the strings.
var element = $('<p>My paragraph has images like this <img src="foo"/> and this <img src="bar"/></p>');
element.find('img').remove();
newText = element.html();
console.log(newText);
var content = content.replace(/<img[^>"']*((("[^"]*")|('[^']*'))[^"'>]*)*>/g,"");
It first matches the <img
. Then [^>"']*
matches any character except for >
, "
and '
any number of times. Then (("[^"]*")|('[^']*'))
matches two "
with any character in between (except "
itself, which is this part [^"]*
) or the same thing, but with two '
characters.
An example of this would be
"asf<>!('"
or'akl>"<?'
.
This is again followed by any character except for >
, "
and '
any number of times. The Regex concludes when it finds a >
outside a set of single or double quotes.
This would then account for having >
characters inside attribute strings, as pointed out by @Derek 朕會功夫 and would therefore match and remove all four image tags in the following test scenario:
<img src="blah.png" title=">:(" alt=">:)" /> Some text between <img src="blah.png" title="<img" /> More text between <img /><img src='asdf>' title="sf>">
This is of course inspired by @Matt Coughlin's answer.
To do this without regex or libraries (read jQuery), you could use DOMParser to parse your string, then use plain JS to do any manipulations and re-serialize to get back your string.
$('<p>').html(content).find('img').remove().end().html()
var content = content.replace(/<img[^>]*>/g,"");
[^>]*
means any number of characters other than >
. If you use .+
instead, if there are multiple tags the replace operation removes them all at once, including any content between them. Operations are greedy by default, meaning they use the largest possible valid match.
/g
at the end means replace all occurrences (by default, it only removes the first occurrence).