ECMAScript提供了replace()方法。這個方法接收兩個參數,第一個參數可以是一個RegExp對象或者一個字元串,第二個參數可以是一個字元串或者一個函數。現在我們來詳細講解可能出現的幾種情況。
1. 兩個參數都為字元串的情況
1 var text = 'cat, bat, sat, fat';
2 // 在字元串中找到at,并将at替換為ond,隻替換一次
3 var result = text.replace('at', 'ond');
4 // "cond, bat, sat, fat"
5 console.log(result);
2. 第一個參數為RegExp對象,第二個參數為字元串
我們可以發現上面這種情況隻替換了第一個at,如果想要替換全部at,就必須使用RegExp對象。
1 var text = 'cat, bat, sat, fat';
2 // 使用/at/g 在全局中比對at,并用ond進行替換
3 var result = text.replace(/at/g, 'ond');
4 // cond, bond, sond, fond
5 console.log(result);
3. 考慮RegExp對象中捕獲組的情況。
RegExp具有9個用于存儲捕獲組的屬性。$1, $2...$9,分别用于存儲第一到九個比對的捕獲組。我們可以通路這些屬性,來擷取存儲的值。
1 var text = 'cat, bat, sat, fat';
2 // 使用/(.at)/g 括号為捕獲組,此時隻有一個,是以所比對的值存放在$1中
3 var result = text.replace(/(.at)/g, '$($1)');
4 // $(cat), $(bat), $(sat), $(fat)
5 console.log(result);
4. 第二個參數為函數的情況,RegExp對象中不存在捕獲組的情況。
1 var text = 'cat, bat, sat, fat';
2 // 使用/at/g 比對字元串中所有的at,并将其替換為ond,
3 // 函數的參數分别為:目前比對的字元,目前比對字元的位置,原始字元串
4 var result = text.replace(/at/g, function(match, pos, originalText) {
5 console.log(match + ' ' + pos);
6 return 'ond'
7 });
8 console.log(result);
9 // 輸出
10 /*
11 at 1 dd.html:12:9
12 at 6 dd.html:12:9
13 at 11 dd.html:12:9
14 at 16 dd.html:12:9
15 cond, bond, sond, fond dd.html:16:5
16 */
5. 第二個參數為函數的情況,RegExp對象中存在捕獲組的情況。
1 var text = 'cat, bat, sat, fat';
2 // 使用/(.at)/g 比對字元串中所有的at,并将其替換為ond,
3 // 當正規表達式中存在捕獲組時,函數的參數一次為:模式比對項,第一個捕獲組的比對項,
4 // 第二個捕獲組的比對項...比對項在字元串中的位置,原始字元串
5 var result = text.replace(/.(at)/g, function() {
6 console.log(arguments[0] + ' ' + arguments[1] + ' ' + arguments[2]);
7 return 'ond'
8 });
9 console.log(result);
10 // 輸出
11 /*
12 cat at 1
13 bat at 6
14 sat at 11
15 fat at 16
16 cond, bond, sond, fond
17 */
以上為replace方法的所有可以使用的情況,下面我們使用replace和正規表達式共同實作字元串trim方法。
1 (function(myFrame) {
2 myFrame.trim = function(str) {
3 // ' hello world '
4 return str.replace(/(^\s*)|(\s*$)/g, '');
5 };
6 window.myFrame = myFrame;
7 })(window.myFrame || {});
8 // 測試
9 var str = ' hello world '
10 console.log(str.length); // 15
11 console.log(myFrame.trim(str).length); // 11