收录JavaScript正则深拷贝的一个方法

2020-03-28  本文已影响0人  RexingLeung

正则深拷贝的一个方法

注意点

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

上一篇 下一篇

猜你喜欢

热点阅读