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.

2
  • 4
    Parsing HTML with regexp's is bad, m'kay? stackoverflow.com/questions/1732348/… Commented Oct 29, 2010 at 13:43
  • is something stopping you from using getElementsByTagName? Commented Oct 29, 2010 at 14:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.