首页 新闻 赞助 找找看

正则匹配 & ' " < >

0
悬赏园豆:15 [已解决问题] 解决于 2011-07-20 22:29

function(str) {
str
= dr.ConvertToString(str);
while (/&/.test(str)) {
str
= str.replace(/&/, "&amp;");
}
while (/'/.test(str)) {
str
= str.replace(/'/, "&apos;");
}
while (/"/.test(str)) {
str
= str.replace(/"/, "&quot;");
}

while (/</.test(str)) {
str
= str.replace(/</, "&lt;");
}
while (/>/.test(str)) {
str
= str.replace(/>/, "&gt;");
}

return str;
}

怎么改比较好?这样写会让人觉得正则基础太差.

问题补充:

while (/&/.test(str)) {
str
= str.replace(/&/, "&amp;");
}
//晕
~不看不知道~发现一个bug啊~~

dotNetDR_的主页 dotNetDR_ | 老鸟四级 | 园豆:2078
提问于:2011-07-20 10:22
< >
分享
最佳答案
0

基础确实不好,不要用 while,也不要用 test,如下:

s = s.replace(/\"/g,"&quot;");
s
= s.replace(/</g,"&lt;");
s
= s.replace(/>/g,"&gt;");

参考下:

http://www.strictly-software.com/htmlencode

http://www.strictly-software.com/scripts/downloads/encoder.js

收获园豆:15
鹤冲天 | 老鸟四级 |园豆:2379 | 2011-07-20 16:51
其他回答(1)
0

看实际需求 普陀的替换字符 就这样用吧

Micheas | 园豆:225 (菜鸟二级) | 2011-07-20 11:02
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册