Trying to replace html tags using regex

半腔热情 提交于 2019-12-06 04:10:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!