用JavaScript實現全域替換,解決$等特殊符號的難題[

來源:互聯網
上載者:User

感謝海浪提供的正則,原貼請參見:
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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.