Dan Dan - 1 year ago 66
Javascript Question

Replace opening and closing HTML tags with regex

I have the following markup:

<span style="font-size: 24px;"><font face="Courier New">[[code]]</font></span><br><p></p><span>{{name}}</span><span>[[otherCode]] </span>

and I'd need to replace the span only wrapping double brackets sequences. So in the case above I'd need to obtain:

<div style="font-size: 24px;"><font face="Courier New">[[code]]</font></div><br><p></p><span>{{name}}</span><div>[[otherCode]] </div>

(ie. the span surrounding {{name}} are not changed.

I know that regular expressions are usually not recommended but in this case I feel it's the only option I have. (FYI I do have jQuery and DOM access if you feel these would be better options.)

So far I've been trying with regex but can't seem to make it avoid the
case. This is what I currently have:


and I think that the solution goes towards stopping at the first span closing tag.

Answer Source

Assuming that you just want to avoid HTML with {s, you can use some variation on this regex:


To ensure that there is a [[ ]] between the span, you can change the regex to this:


Let me rewrite that with some spacing:

   [^{]*?   \[\[   [^\]]*   \]\]   [^{]*?

(Note that you may have to escape the /.)

Since you want to replace the spans with divs, you can add capturing parenthesis like this:


Your replacement should be: <div$1div>.

This works when I test it online on your one sample, but it will fail if there are certain characters in the HTML. It might also break depending on the HTML structure, especially if it's poorly formed.

It might be easier to use a real parser in those cases. Alternatively, you might still be able to use the regex is you are able to break up the HTML and ensure that you are only passing chunks it can successfully work on.