09-07
08

JavaScript 中的replace方法,正则或字符串全部交替

第一次发现javascript中replace() 方法如果直接用str.replace("-","!") 只会替换第一个匹配的字符.

引用内容 引用内容
replace()
The replace() method returns the string that results when you replace text matching its first argument
    (a regular e­xpression) with the text of the second argument (a string).
    If the g (global) flag is not set in the regular e­xpression declaration, this method replaces only the first
    occurrence of the pattern. For example,

var s = "Hello. Regexps are fun.";s = s.replace(/\./, "!"); // replace first period with an exclamation pointalert(s);

produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
    perform a global replace, finding and replacing every matching substring. For example,

var s = "Hello. Regexps are fun.";s = s.replace(/\./g, "!"); // replace all periods with exclamation pointsalert(s);

yields this result: “Hello! Regexps are fun!”


以上是对于交替普通字符串的写法,如果正则表达式,交替方法如下:

因为js不支持类似 /<(?!(a|img))[^>]*(?<!(a|img))>/ 的零宽度正回顾后发断言的正则方式,这题用正则就比较麻烦了

假如需要保留的部分不会被其他标签包含,可以这样:

str.replace(/<font .*?<\/font>/ig,"").
replace(/<script .*?<\/script>/ig,"").
replace(/<(a|img)/ig, "@@@$1").
replace(/<[^>a]*>/ig, "").
replace(/@@@(a|img)/ig, "<$1");


简单测试通过....不知道实用性如何,没有考虑复杂情况


1.清除HTML格式:

假设原字符串是用\r\n分行,获取的结果以<br />分行,HTML字符串符合XHTML标准

则有: str.replace(/<[^>]*>/g, "").replace(/\r\n/g, "<br />");


试运行:
<script language="javascript" type="text/javascript">
var str = "<li><a href025616163715.shtml TARGET=_blank>职称不再要求</a><FONT style=\"FONT-SIZE:12px\"> (8月24日)</FONT>\r\n" +
"<li><a href=025616163704.shtml TARGET=_blank>火公园今日将提前限客</a><FONT style=\"FONT-SIZE:12px\"> (8月24日)</FONT>";
document.write(str.replace(/<[^>]*>/g, "").replace(/\r\n/g, "<br />"));
</script>

2.清除font
前提,字符串符合XHTML标准(即元素闭合正常)
str.replace(/<font .*?<\/font>/ig,"");


[本日志由 blurxx 于 2009-07-08 01:52 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: JS replace all 正则
相关日志:
评论: 0 | 引用: 0 | 查看次数: 327
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭