0

I have a html string like <FONT id="test" face="Arial"><SPAN><P>This is some content...</P></SPAN></FONT>. Now using javascript regex I want to remove the font tag with id test and the span tag with their associated closing tags.

So that the output becomes <P>This is some content...</P> .How to do this ?

Marc B
  • 356,200
  • 43
  • 426
  • 500
Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70
  • do you need the

    tags surrounding the text ?

    – Manse Nov 04 '11 at 15:43
  • 4
    Don't use regexes on HTML: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 JS is already perfectly capable of manipulating the DOM without any regexes at all. – Marc B Nov 04 '11 at 15:43
  • yes..there may be some other tags also surrounding the text – Hector Barbossa Nov 04 '11 at 15:43

2 Answers2

1

It is generally agreed upon that using Regex to parse HTML is a bad idea. I would recommend you use jQuery to parse this into DOM elements and then manipulate it.

var content = $('<FONT id="test" face="Arial"><SPAN><P>This is some content...</P></SPAN></FONT>').find('span').children();

Or use (but I wouldn't recommend it) the DOM api itself:

var str = '<FONT id="test" face="Arial"><SPAN><P>This is some content...</P></SPAN></FONT>';
var div = document.createElement('div');
div.innerHTML = str;
var newStr = div.getElementsByTagName('span')[0].innerHTML;
console.log(newStr);

http://jsfiddle.net/hhRYX/

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
0

You could try this -> http://jsfiddle.net/manseuk/hAPzQ/

script :

var testdom = document.getElementById('test');
var replacedom = testdom.childNodes[0].childNodes[0];
testdom.parentNode.replaceChild(replacedom,testdom);

.replaceChild() is cross-browser -> http://www.quirksmode.org/dom/w3c_core.html#nodemanipulation

Manse
  • 37,765
  • 10
  • 83
  • 108