當replace()方法的第二個參數是函數而不是字符串時,將這個函數的返回字符串作爲替換文本使用,這個函數是自定義的替換規則。
該函數的參數說明
當正則沒有分組的時候
- 第一個參數是正則捕獲到的內容
- 第二個參數是捕獲的內容在原字符串中的索引位置
- 第三個參數是原字符串
var camelizeRE = /-/g;
var str = 'name-zhen'
var newStr = str.replace(camelizeRE,
function() {
console.log('arguments', arguments)
return arguments[0] ? '_' : '';
})
console.log('newStr', newStr)
當正則有分組的時候
- 第一個參數是正則捕獲到的內容
- 第二個參數開始各個分組(子正則)查找到的內容
- …
- 倒數第二個參數是總正則捕獲的內容在原字符串中的索引位置
- 最後一個參數是原字符串
var camelizeRE = /-(\w)/g;
var str = 'name-zhen'
var newStr = str.replace(camelizeRE,
function() {
console.log('arguments', arguments)
return arguments[1] ? arguments[1].toUpperCase() : '';
})
console.log('newStr', newStr)
正則表達式分組的概念:就是正則表達式中用()包起來的內容代表了一個分組