Question

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?

Was it helpful?

Solution

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

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

OTHER TIPS

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>

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top