Close HTML img tag

1

I'm getting an html string from a text editor called froala , but this editor does not close the img tags.

How could I take an html string that contains tags of this type:

<img src="rutaxx" alt="altxx" class="classxxx">

and pass them to this:

<img src="rutaxx" alt="altxx" class="classxxx"/>
    
asked by Natali Gamboa 23.07.2018 в 14:28
source

1 answer

1

This function could help you:

First we remove the blank spaces at the beginning and end with trim .

Then we get all tags of type img with the following regex using the function match :

/(<(img[^>]+)>)/ig

This will generate an array of strings with tag type format img .

Then we insert the tag closing slash at the end of your string using the slice and we reinsert the modified tag into the string.

var cadena = ' <p><img src="i0.wp.com/wptavern.com/wp-content/uploads/2016/07/…\" class=\"fr-fic fr-dii\" style=\"width: 228px;"></p><p><span style="color: rgb(226, 80, 65);">esto es un parrafo en rojo</span></p> ';

// Quitamos los espacios en blanco
cadena = cadena.trim();

//Buscamos las etiquetas img dentro de la cadena
var tags = cadena.match(/(<(img[^>]+)>)/ig);
if (tags != null) {
  tags.forEach(function(tag, i) {

    // Guardamos la posición de la etiqueta
    var position = cadena.indexOf(tag);

    // Eliminamos la antigua etiqueta
    cadena = cadena.replace(tag, '');

    // Agregamos el "/" antes de cerrar la cadena
    tag = tag.slice(0, tag.length - 1) + "/" + tag.slice(tag.length - 1);

    // Insertamos la nueva etiqueta en la cadena
    cadena = [cadena.slice(0, position), tag, cadena.slice(position)].join('');

  });
}

console.log("Nueva Cadena: \n\n" + cadena);
    
answered by 23.07.2018 / 15:33
source