问题描述:

I have the code

let dirtyHtml = `<img class="emojione" src="">

<img class="a" src="edw">

<img class="emojione" src="" />

<img class="emojione" src=""/>

<img src="">`;

let clearHtml = dirtyHtml.replace(/<img[^<>]+(?!emojione)[^<>]+>/gi, '');

console.log(clearHtml);

网友答案:

/<img(?:(?!emojione).)*>/gi will match anything between <img and > that doesn't contain the string emojione. Like this:

let dirtyHtml = `<img class="emojione" src="">
<img class="a" src="edw">
<img class="emojione" src="" />
<img class="emojione" src=""/>

<img src="">`;

let clearHtml = dirtyHtml.replace(/<img(?:(?!emojione).)*>/gi, '');

console.log(clearHtml);
网友答案:

You can try this (doesn't matter img whether [a-z]{3} because src's supported elements have more than 3 chars http://www.w3resource.com/html/attributes/html-src-attribute.php but it's easier to write img)

let dirtyHtml = `<img class="emojione" src="">
<img class="a" src="edw">
<img class="emojione" src="" />
<img class="emojione" src=""/>

<img src="">`;

let clearHtml = dirtyHtml.replace(/(<img class="[a-z]?" src="[a-z]+">)|(<img src="">)/gi, '');

console.log(clearHtml);
网友答案:

I won't repeat many reasons why RegExp usage to modify HTML is a bad idea (and by many considered as a hack), but I would like to show how natural it could be to use jQuery for this task

let dirtyHtml = `<img class="emojione" src="">
<img class="a" src="edw">
<img class="emojione" src="" />
<img class="emojione" src=""/>

<img src="">`;

// Put your html string within some HTML element to make a starting point
var $wrap = $('<div/>').append(dirtyHtml);
// Remove image tags without specific class
$wrap.find('img:not(.emojione)').remove();

console.log($wrap.html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
相关阅读:
Top