-1

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);

I expect to see this

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

But I'll see empty string...

What wrong with my regular expression?

constantant
  • 1,192
  • 1
  • 13
  • 25

3 Answers3

2

/<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);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

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);
grzesiekmq
  • 419
  • 1
  • 6
  • 17
0

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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Community
  • 1
  • 1
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
  • Please, repeat this solution without jQuery – constantant Feb 18 '17 at 20:14
  • I was asking for this: `const dirtyDom = document.createElement('div'); dirtyDom.innerHTML = ''; dirtyDom.querySelectorAll('img:not(.emojione)').forEach(node => dirtyDom.removeChild(node));`. Thanks :) – constantant May 26 '21 at 10:57