Removing image elements from a row

I have a string containing HTML image elements that are stored in var.

I want to remove image elements from a string.

I tried: var content = content.replace(/<img.+>/,"");

and: var content = content.find("img").remove(); but no luck.

Can anyone help me at all?

thanks

+4
source share
7 answers
 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 in between. Operations are greedy by default, that is, they use the maximum possible matching.

/g at the end means replacing all occurrences (by default it removes only the first occurrence).

+18
source

Use text() , it will remove all HTML tags!

 var content = $("<p>"+content+"</p>").text(); 
+6
source
 $('<p>').html(content).find('img').remove().end().html() 
+5
source

The following regex should do the trick:

 var content = content.replace(/<img[^>"']*((("[^"]*")|('[^']*'))[^"'>]*)*>/g,""); 

First it matches <img . Then [^>"']* any number of characters is executed except > , " and ' . Then (("[^"]*")|('[^']*')) matches the two " with any character between them (except " which is this part [^"]* ) or the same, but with two characters ' .

An example of this would be "asf<>!('" Or 'akl>"<?' .

This is followed again by any character except > , " and ' as many times as necessary. Regex terminates when it finds > outside a set of single or double quotes.

Then it would take into account the presence of > characters inside the attribute strings, as @Derek 朕 會 功夫 indicated , and therefore would 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, of course, is inspired by @Matt Coughlin 's answer.

+2
source

Does this work for you ?:

 var content = content.replace(/<img[^>]*>/g, '') 
0
source

You can load the text as a DOM element and then use jQuery to find all the images and delete them. Usually I try to treat XML (html in this case) as XML and do not try to parse 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); 
0
source

I'm in IE right now ... this works fine, but my tags are uppercase (after using innerHTML, I think) ... so I added "i" to make the case insensitive. Now Chrome and IE are happy.

 var content = content.replace(/<img[^>]*>/gi,""); 
0
source

All Articles