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