tags:

views:

46

answers:

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.

A: 

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