Remove image elements from string

前端 未结 8 2091
独厮守ぢ
独厮守ぢ 2021-02-20 16:47

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 =

相关标签:
8条回答
  • 2021-02-20 17:29

    Does this work for you?:

    var content = content.replace(/<img[^>]*>/g, '')
    
    0 讨论(0)
  • 2021-02-20 17:37

    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);
    
    0 讨论(0)
  • 2021-02-20 17:37

    The following Regex should do the trick:

    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.

    0 讨论(0)
  • 2021-02-20 17:41

    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.

    0 讨论(0)
  • 2021-02-20 17:41
    $('<p>').html(content).find('img').remove().end().html()
    
    0 讨论(0)
  • 2021-02-20 17:43
    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).

    0 讨论(0)
提交回复
热议问题