字符串的替換函數replace平常使用的頻率非常高,format函數通常用來填補占位符。下面簡單總結一下這兩個函數的用法。
一、String.replace的兩種用法
replace的用法如:replace(regexp, string|fn);第一個參數都是正則表達式,第二個參數可以是要替換的字符串,也可以是帶返回值的函數,它的功能就是拿第二個參數替換匹配的值。
1.replace(regexp, string):我想把“樂小天”中的“小”替換成“大”,如下所示。
console.log("樂小天".replace(/小/g, "大"));//樂大天
//trim的實現方式 console.log(" 樂小天 ".replace(/(^\s+)|(\s+$)/g, ""));//樂小天
2.replace(regexp, fn);fn這個回調函數可以有四種參數,第一種參數是匹配regexp的字符串;第二種為匹配regexp子表達式的字符串(有幾個自表達式,順延對應幾個參數,如果沒有子表達式,則第二個參數為第三種參數);第三種參數為regexp匹配字符串在字符串中的索引;第四種參數為當前調用replace的字符串。
拿上面trim的實現為例,它的正則表達式包含兩個子表達式:(^\s+)和(\s+$);所以回調函數應該有5個參數。當然,如果沒有子表達式,則只有三種參數。
console.log(" 樂小天 ".replace(/(^\s+)|(\s+$)/g, function(match, matchChild1, matChild2, index, strObj){ console.log("match:" + match + ";"); console.log("matchChild1:" + matchChild1 + ";"); console.log("matChild2:" + matChild2 + ";"); console.log("index:" + index + ";"); console.log("strObj:" + strObj + ";"); return ""; } )); /** match: ; matchChild1: ; matChild2:undefined; index:0; strObj: 樂小天 ; match: ; matchChild1:undefined; matChild2: ; index:11; strObj: 樂小天 ; 樂小天 */
二、String.format的實現
有的時候我們事先不知道字符串對應位置應該替換成什么,所以我們用占位符“{數字}”在字符串中進行預先占位,在真正確定的時候才將其替換掉。說白了就是將未知的替換字符封裝成參數,讓替換邏輯這個不變的部分與替換參數這個變化部分進行分離。
1.format實現:
//擴展format String.prototype.format = String.prototype.format || function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match; }); }; console.log("{0}是個{1}帥哥!".format('孫悟空', '大'));//孫悟空是個大帥哥!
2.format替換字符在form校驗中用到的比較多,比如前端UI框架MiniUI的校驗對象VType是這么定義的:
mini.VTypes = { minDateErrorText : "Date can not be less than {0}", maxDateErrorText : "Date can not be greater than {0}", ... };
在返回錯誤信息的時候將對應的邊界值替換掉“{0}”