问题
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?
回答1:
You have keep the opening and closing tag brackets. So try this:
o.replace(/(<\s*\/?\s*)script(\s*([^>]*)?\s*>)/gi ,'$1div$2')
回答2:
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>
回答3:
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);
}
来源:https://stackoverflow.com/questions/849969/trying-to-replace-html-tags-using-regex