DIV CSS 佈局教程網

用正則實現 JS 的 ReplaceAll 全部替換
編輯:關於JavaScript     

JS 字符串有 replace() 方法,但它只會替換匹配到的第一個字符串。如下例:

 var str = "wordwordwordword";
 var strNew = str.replace("word","Excel");
 alert(strNew); // 只替換了第一個 word

如果要全部替換,JS 並沒有提供 replaceAll 這樣的方法。借助正則表達式就能達到 Replace 的效果:

 str.replace(/word/g,"Excel")

其中 g 的意義是:執行全局匹配(查找所有匹配,而非找到第一個就停止)。

 function replaceAll(str) {
 if(str!=null) str = str.replace(/word/g,"Excel")
 return str;
 }

還有一種類似的寫法:

 str.replace(new RegExp("word","gm"),"Excel")

其中 g 執行全局匹配,m 執行多行匹配。

除此之外,也可以給 String 對象添加原型方法:

 String.prototype.replaceAll = function(s1,s2){
 return this.replace(new RegExp(s1,"gm"),s2);
 }

這樣就能像使用 replace 一樣使用 replaceAll 了:

 str.replaceAll("word","Excel");

總結一下,共有三種方式:

1. str.replace(/oldString/g, newString)

2. str.replace(new RegExp(oldString,"gm"), newString)

3. 給 String 對象增加原型方法 replaceAll

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved