¿Hay una manera fácil de convertir el HTML con múltiples etiquetas apropiadas
en etiquetas

alrededores en Javascript?

StackOverflow https://stackoverflow.com/questions/1275250

Pregunta

Vamos a decir que tengo un montón de HTML, como a continuación:

bla bla bla long paragraph here
<br/>
<br/>
bla bla bla more paragraph text
<br/>
<br/>

¿Hay una manera fácil con Javascript para convertirlo en etiquetas semánticas <p> correctamente? Por ejemplo:.

<p>
  bla bla bla long paragraph here
</p>
<p>
  bla bla bla more paragraph text
</p>

espaciamiento de salida no es importante, lo ideal sería que funcionará con cualquier separación de entradas.

Estoy pensando que podría tratar de cocinar una expresión regular, pero antes de hacerlo que quería asegurarse de que estaba a) evitar un mundo de dolor y b) no había algo más por ahí - que había tratado de hacer una búsqueda en google, pero aún no han llegado a nada.

Gracias por cualquier consejo!

¿Fue útil?

Solución

Me aburrí. Estoy seguro de que hay optimizaciones / ajustes necesarios. Utiliza un poco de jQuery para hacer su magia. Trabajado en FF3. Y la respuesta a su pregunta es que no hay una manera muy "simple":)

$(function() {
  $.fn.pmaker = function() {
    var brs = 0;
    var nodes = [];

    function makeP()
    {
      // only bother doing this if we have nodes to stick into a P
      if (nodes.length) {
        var p = $("<p/>");
        p.insertBefore(nodes[0]);  // insert a new P before the content
        p.append(nodes); // add the children        
        nodes = [];
      }
      brs=0;
    }

    this.contents().each(function() {    
      if (this.nodeType == 3) // text node 
      {
        // if the text has non whitespace - reset the BR counter
        if (/\S+/.test(this.data)) {
          nodes.push(this);
          brs = 0;
        }
      } else if (this.nodeType == 1) {
        if (/br/i.test(this.tagName)) {
          if (++brs == 2) {
            $(this).remove(); // remove this BR from the dom
            $(nodes.pop()).remove(); // delete the previous BR from the array and the DOM
            makeP();
          } else {
            nodes.push(this);
          }
        } else if (/^(?:p)$/i.test(this.tagName)) {
          // these tags for the P break but dont scan within
          makeP();
        } else if (/^(?:div)$/i.test(this.tagName)) {
          // force a P break and scan within
          makeP();
          $(this).pmaker();
        } else {
          brs = 0; // some other tag - reset brs.
          nodes.push(this); // add the node 
          // specific nodes to not peek inside of - inline tags
          if (!(/^(?:b|i|strong|em|span|u)$/i.test(this.tagName))) {
            $(this).pmaker(); // peek inside for P needs            
          }
        } 
      } 
    });
    while ((brs--)>0) { // remove any extra BR's at the end
      $(nodes.pop()).remove();
    }
    makeP();
    return this;
  };

  // run it against something:
  $(function(){ 
    $("#worker").pmaker();
  });

Y esta era la porción html Probé contra:

<div id="worker">
bla bla bla long <b>paragraph</b> here
<br/>
<br/>
bla bla bla more paragraph text
<br/>
<br/>
this text should end up in a P
<div class='test'>
  and so should this
  <br/>
  <br/>
  and this<br/>without breaking at the single BR
</div>
and then we have the a "buggy" clause
<p>
  fear the real P!
</p>
and a trailing br<br/>
</div>

Y el resultado:

<div id="worker"><p>
bla bla bla long <b>paragraph</b> here
</p>
<p>
bla bla bla more paragraph text
</p>
<p>
this text should end up in a P
</p><div class="test"><p>
  and so should this
  </p>
  <p>
  and this<br/>without breaking at the single BR
</p></div><p>
and then we have the a "buggy" clause
</p><p>
  fear the real P!
</p><p>
and a trailing br</p>
</div>

Otros consejos

Analiza cada uno de los elementos secundarios + texto del elemento envolvente. Cada vez que encuentro un elemento "ancho", crear un elemento "p", y añadir toda la materia pendiente de ella. Lather, enjuague, repita.

No se olvide de quitar el material que se está mudando a un nuevo elemento "p".

He encontrado esta biblioteca (prototype.js) ser útil para este tipo de cosa.

Estoy asumiendo que usted no está realmente permitiendo que cualquier otra A veces es necesario para preservar individuales saltos de línea (no todos los elementos <br /> son malos), y sólo desea convertir dobles instancias de <br /> en saltos de párrafo.

De este modo lo haría:

  1. Eliminar todos los saltos de línea
  2. Envolver todo el lote en un párrafo
  3. Reemplazar <br /><br /> con </p>\n<p>
  4. Por último, retirar cualquier elemento <p></p> vacíos que podrían haber sido generados

Así que el código podría ser algo como:

var ConvertToParagraphs = function(text) {
    var lineBreaksRemoved = text.replace(/\n/g, "");
    var wrappedInParagraphs = "<p>" + lineBreaksRemoved + "</p>";
    var brsRemoved = wrappedInParagraphs.replace(/<br[^>]*>[\s]*<br[^>]*>/gi, "</p>\n<p>");
    var emptyParagraphsRemoved = brsRemoved.replace(/<p><\/p>/g, "");
    return emptyParagraphsRemoved;
}

Nota:. He estado muy detallado para mostrar los procesos, que le simplificar, por supuesto

Esto convierte su ejemplo:

bla bla bla long paragraph here
<br/>
<br/>
bla bla bla more paragraph text
<br/>
<br/>

En:

<p>bla bla bla long paragraph here</p>
<p>bla bla bla more paragraph text</p>

Pero lo hace sin eliminar ningún elemento <br /> que en realidad se puede desear.

lo haría en varias etapas:

  1. RegExp:. br convertir todas las etiquetas de saltos de línea
  2. RegExp:. Franja de formularios de todo el espacio en blanco
  3. RegExp: Convertir los múltiples saltos de línea a los solos
  4. .
  5. Uso Array.split ( '\ n') en el resultado.

Esto debería dar una matriz con todos los párrafos 'reales' (en teoría). A continuación, sólo puede iterar a través de ella y envolver cada línea de p-tags.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top