1

I need a javascript regex replace function to turn

<font anything_possible><span anything_different_possible></span>

into

<span anything_different_possible></span><font anything_possible>

I tried many combinations but failed. Any help appreciated.

Kelly Lim
  • 65
  • 1
  • 4
  • 4
    Parsing HTML with regexp's is bad, m'kay? http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Jacob Oscarson Oct 29 '10 at 13:43
  • is something stopping you from using getElementsByTagName? – Dawn Oct 29 '10 at 14:25

1 Answers1

1

I think this should do it:

var original = '<font anything_possible><span anything_different_possible></span>';

var replaced = original.replace(/<font (.*?)><span (.*?)><\/span>/,"<font $2><span $1></span>");

Note that the regex matches your 'anything possible' and 'anything_different_possible' pieces, while the replacement-text contains these matches in reverse order ($2 and $1). So: everytime a submatch is made (with round braces()), it is later available as $n.

Hope this solves your problem

Edit:

As some users point out, if this is about manipulating the DOM, it is probably better to use the DOM functions for that.

But i can imagine situations where you might need a string-replace function like this.

zjorzzzey
  • 94
  • 3