views:

550

answers:

3

For the example, I'm trying to replace

<script type='text/javascript'>some stuff</script>

with:

<div type='text/javascript'>some stuff</div>

I'm currently testing with:

alert( o.replace( /(?:<\s*\/?\s*)(script)(?:\s*([^>]*)?\s*>)/gi ,'div') );

But what I'm getting is:

divsomestuffdiv

How can I get this to only replace the "script" portion and preserve the other markup and attribute characters?

+3  A: 

You have keep the opening and closing tag brackets. So try this:

o.replace(/(<\s*\/?\s*)script(\s*([^>]*)?\s*>)/gi ,'$1div$2')
Gumbo
+1  A: 

DOM methods are better suited for this than regular expressions. This way you'll manipulate your document logically instead of as plaintext:

var els = document.getElementsByTagName('script');
for (var i = 0, el; el = els[i]; i++) {
    var new = document.createElement('div');
    new.type = el.type;
    el.parentNode.replaceChild(el, new);
}
a paid nerd
+1  A: 

A naive but readable way would be to do it in two passes i suppose and first match and replace the

<script

part with

<div

and then another which would match

</script>

and replace it with

</div>

Simonw