收錄JavaScript正則深拷貝的一個方法

正則深拷貝的一個方法

注意點

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地址

cloneRegExp

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章