最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trying to replace html tags using regex - Stack Overflow

programmeradmin12浏览0评论

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?

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?

Share Improve this question asked May 11, 2009 at 20:37 GeuisGeuis 42.3k57 gold badges163 silver badges223 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

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

o.replace(/(<\s*\/?\s*)script(\s*([^>]*)?\s*>)/gi ,'$1div$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>

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);
}
发布评论

评论列表(0)

  1. 暂无评论