Trying to replace html tags with regex

As an example, I'm trying to replace

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

with:

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

I am currently testing:

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

But I get:

 divsomestuffdiv 

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

+4
source share
3 answers

You have brackets for opening and closing tags. So try the following:

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

DOM methods are better suited for this than regular expressions. This way you will manipulate your document logically, and not as plain text:

 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); } 
+2
source

A naive but readable way would be to do this in two passes, and suppose that we first compare and replace

<script

part with

<div

and then another one that will match

</script>

and replace it with

</div>

+2
source

All Articles