How to remove img tags from a text?

7

I need to remove all img tags from text in javascript. So the pictures do not come.
Note: The text is random.

How to do it:

Vestibulum varius lectus a ante euismod <img src="teste2.jpg"> cursus. Nam sed semper augue, a laoreet purus. <img src="teste.jpg"> Vivamus ut risus eu lectus imperdiet sollicitudin.

How_you should:

Vestibulum varius lectus a ante euismod cursus. Nam sed semper augue, a laoreet purus. Vivamus ut risus eu lectus imperdiet sollicitudin.
    
asked by anonymous 28.04.2017 / 16:07

2 answers

10

You can use a temporary element to clean it up.

I usually do this:

function limparHTML(html) {
  const proxy = document.createElement('div');
  proxy.innerHTML = html;
  return proxy.innerText;
}

const HTML = 'Vestibulum varius lectus a ante euismod <img src="teste2.jpg"> cursus. Nam sed semper augue, a laoreet purus. <img src="teste.jpg"> Vivamus ut risus eu lectus imperdiet sollicitudin.';

const limpo = limparHTML(HTML);
alert(limpo);

If you are in Node.js environment or you can not use elements like I suggested, you can try RegExp.

In this case it might look like this:

function limparHTML(html) {
  return html.replace(/<img[^>]*>/g, '');
}

const HTML = 'Vestibulum varius lectus a ante euismod <img src="teste2.jpg"> cursus. Nam sed semper augue, a laoreet purus. <img src="teste.jpg"> Vivamus ut risus eu lectus imperdiet sollicitudin.';

const limpo = limparHTML(HTML);
alert(limpo);

The idea of /<img[^>]+>/g is:

  • must have the string <img
  • After the string (above) [^>]* means "any character, excluding > zero or more times"
  • end with the character '>' '
  • g means "globally" in all occurrences
In the first version of my response with regex I had [^>]+ , but I changed to * , zero or more times, and #
28.04.2017 / 16:10
5

You can also use the following expression for this:

var textoConvertido = html.replace(/<img[^>]*>/g, '');

See the example below:

var html = 'Vestibulum varius lectus a ante euismod <img src="teste2.jpg"> cursus. Nam sed semper augue, a laoreet purus. <img src="teste.jpg"> Vivamus ut risus eu lectus imperdiet sollicitudin.';
var textoConvertido = html.replace(/<img[^>]*>/g, '');

console.log(textoConvertido);
    
28.04.2017 / 16:33