正則深拷貝的一個方法
注意點
reg.exec(str|regObj), MDN上面exec只是說了接受字符串, 但是也可以接收正則對象
regexp.constructor如果報flag的問題, 一般是第二個參數傳錯了
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
const reg = /foo/g
let reg2 = cloneRegExp(reg) // /foo/g
console.log(reg2);
git地址