2012-07-11 11 views
7

Ho una variabile che contiene una stringa di testo e HTML tag, come ad esempio:Jquery: Striscia di tutti i tag HTML specifici da stringa

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 

vorrei per rimuovere tutti i tag di un certo tipo. Diciamo tutti i tag p e span ad esempio.

Questo è il meglio che posso venire con:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 
var $temp = $(temp); 
$("p", $temp).replaceWith("foo"); 
alert($temp.html()); //returns "Some text" 

La risposta più vicina che ho trovato è questa risposta da Nick Craver: strip span tags from string with jquery.

+0

cosa è che _certain TYPE_? – undefined

+0

domanda modificata: tag p e tag span sono ciò che voglio sostituire. Ma questo potrebbe cambiare in futuro. – iammatthew2

risposta

12

Demo: http://jsfiddle.net/VwTHF/1/

$('span, p').contents().unwrap(); 

.contents() otterrà gli elementi e il testo all'interno di ciascuna di tali tag, e .unwrap rimuoverà l'elemento avvolgendo ogni sezione contenuti.

Sulla base della sua attuale approccio sarebbe simile a questa:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 
var $temp = $(temp); 
$temp.find('span, p').contents().unwrap().end().end(); 

Se si desidera continuare mira l'oggetto originale, è necessario utilizzare .end() per cancellare il filtro.

+0

Spero di non aver frainteso la tua domanda. Stai solo cercando di sbarazzarti dei tag ma lascia il testo giusto? – nbrooks

+0

Sì, voglio solo rimuovere determinati tag e mantenere il testo e tutti gli altri tag. Ma in questo esempio non sono riuscito a ottenere quanto sopra: [http://jsfiddle.net/nEFhA/] – iammatthew2

+0

@ iammatthew2 Funziona perfettamente. Hai dimenticato di includere jQuery: http: // jsfiddle.net/WPpqE/(devi specificare il framework da usare nelle opzioni a sinistra) – nbrooks

2

Si potrebbe provare il jquery plugin HTML Clean. Nell'esempio che forniscono:

$.htmlClean("<H1 class=\"header\"><P>Nested P Test</H1>", {format:true}); 

=> 
<h1> 
     Nested P Test 
</h1> 

È possibile sostituire i tag specifici con {removeTags:[p]} e sarà ancora rendere i contenuti non solo il tag.

+0

Grazie! Farò un tentativo, ma stavo pensando che Jquery potesse occuparsi di questo con solo poche righe di codice. – iammatthew2

0

Ho dovuto fare qualcosa di simile: mantenere un blocco di testo dal contenere qualsiasi tag HTML diverso da <b>, <i> o <u>. Questa domanda e molti altri mi hanno indirizzato verso la mia funzione:

function cleanNonFormattingTags(htmlContents) { 
    if (htmlContents && htmlContents.length) { 
     var result = ''; 
     htmlContents.each(function() { 
      var $child = $(this), type = $child.prop('tagName'), isTextNode = this.nodeName == "#text"; 
      if (isTextNode) { 
       result += this.textContent; 
      } 
      else if (type == 'B' || type == 'U' || type == 'I' || type == 'BR') { // Allow only these types of tags 
       var innerContent = cleanNonFormattingTags($child.contents()); 
       var $newTag = $(document.createElement(type)).html(innerContent); 
       result += $newTag[0].outerHTML; 
      } 
      else { 
       result += cleanNonFormattingTags($child.contents()); 
      } 
     }); 
     return result; 
    } 
    return htmlContents.text(); 
} 

Spero che questo aiuti!

0

Seguirò @nbrooks perché la sua risposta è molto vicina a ciò che si desidera, ma non del tutto. @nbrooks ha colpito la soluzione notando che html() ti fornisce i dati che sono racchiusi in un tag. La soluzione è quindi avvolgere il tuo HTML in un tag. Questo dovrebbe fare il trucco per voi:

var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; 
$("<span>" + temp + "</span>").find('span,p'). 
    contents().unwrap().end().end().html()` 

Vedi http://jsfiddle.net/18u5Ld9g/1/ per un esempio.

Come una funzione più generale:

function stripTags(html, tags) { 
    // Tags must be given in CSS selector format 
    return $("<span>" + html + "</span>").find(tags). 
    contents().unwrap().end().end().html(); 
} 
Problemi correlati