感謝海浪提供的正則,原貼請參見:
http://www.iecn.net/bbs/view/106503.html
因為要做個模板替換的東西,裡面的變數採用${MyName}這種格式的命名方式。在進行全域替換時,遇到兩個痛點:
1.要麼無法替換掉$等特殊符號
2.要麼無法忽略大小寫
在海浪有協助下,終於有了最佳實現方式:)
最佳實現方式: 複製代碼 代碼如下:<script type="text/javascript">
String.prototype.replaceAll = stringReplaceAll;
function stringReplaceAll(AFindText,ARepText){
var raRegExp = new RegExp(AFindText.replace(/([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])/g,"\\$1"),"ig");
return this.replace(raRegExp,ARepText);
}
var ssString="www.cnlei.com;www.CnLei.net;www.cnlei.org";
alert(ssString.replaceAll("cnlei","iecn"));
ssString="www.${MyName}.com;www.${MyName}.net;www.${MyName}.org";
alert(ssString.replaceAll("${MyName}","cnlei"));
ssString="www.{MyName}.com;www.{MyName}.net;www.{MyName}.org";
alert(ssString.replaceAll("{MyName}","cnlei"));
</script>
以前使用方法一:(可實現忽略大小,但無法實現特殊符號的替換) 複製代碼 代碼如下:<script type="text/javascript">
String.prototype.replaceString = stringReplaceAll;
function stringReplaceAll(AFindText,ARepText){
var raRegExp = new RegExp(AFindText,"ig");
return this.replace(raRegExp,ARepText);
}
var ssString="www.cnlei.com;www.CnLei.net;www.cnlei.org";
alert(ssString.replaceString("cnlei","iecn"));
ssString="www.${MyName}.com;www.${MyName}.net;www.${MyName}.org";
alert(ssString.replaceString("${MyName}","cnlei"));
ssString="www.{MyName}.com;www.{MyName}.net;www.{MyName}.org";
alert(ssString.replaceString("{MyName}","cnlei"));
</script>
以前使用的方式二:(可替換特殊符號$等,但無法忽略大小寫) 複製代碼 代碼如下:<script type="text/javascript">
String.prototype.replaceString = function(s1,s2){
this.str=this;
if(s1.length==0)return this.str;
var idx=this.str.indexOf(s1);
while(idx>=0){
this.str=this.str.substring(0, idx)+s2+this.str.substr(idx+s1.length);
idx=this.str.indexOf(s1);
}
return this.str;
}
var ssString="www.cnlei.com;www.CnLei.net;www.cnlei.org";
alert(ssString.replaceString("cnlei","iecn"));
ssString="www.${MyName}.com;www.${MyName}.net;www.${MyName}.org";
alert(ssString.replaceString("${MyName}","cnlei"));
ssString="www.{MyName}.com;www.{MyName}.net;www.{MyName}.org";
alert(ssString.replaceString("{MyName}","cnlei"));
</script>