JavaScript 中的replace方法(全部替换replaceAll效果)
JavaScript中replace() 方法如果直接用str.replace("-","!") 只会替换第一个匹配的字符.
而str.replace(/\-/g,"!")则可以替换掉全部匹配的字符(g为全局标志)。
str.replace(/\'-' /g,"!") '-' 是你想要被替换的字符.
function ieStr2ascii(str) {
var re = /%/g;
str = str.replace(re,"%25");
var re = /=/g;
str = str.replace(re,"%3d");
re = /\?/g;
str = str.replace(re,"%3f");
re = /\'/g;
str = str.replace(re,"%27");
re = /&/g;
str = str.replace(re,"%26");
return str;
}
实例:
function encodeURL(str){
return encodeURI(str).replace(/=/g,"%3D").replace(/\+/g,"%2B").replace(/\?/g,"%3F").replace(/\&/g,"%26");
}
function htmlEncode(str) {
return str.replace(/&/g,"&").replace(/\"/g,""").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ");
}
function htmlDecode(str) {
return str.replace(/\"/g,"\"").replace(/\</g,"<").replace(/\>/g,">").replace(/\ /g," ").replace(/\&/g,"&");
}
本文介绍JavaScript中使用replace方法实现字符串中特定字符的全局替换,并提供了几个实用的字符串处理函数示例,如URL编码、HTML实体编码及解码等。
1085

被折叠的 条评论
为什么被折叠?



