封装一个函数可以一次性把符合正则的所有内容都拿到

183 阅读1分钟

前言

正则的exec属性去捕获一个字符串时一次只能拿一个符合的,因此同样的步骤需要做多次,每次使用exec 或者test ,都会更新对应的lastIndex属性(lastIndex属性是自身内置的属性)

execAll的实现思想

一直用exec捕获 啥时候结果是null 啥时候就停止捕获,先用一个变量接收 exec的结果 ,当这个结果存在 就是把这结果放到一个数组中,当结果不存在时 返回 这个数组;

代码实现

RegExp.prototype.execAll = function(str){
    var that = this;//函数中的this不能直接参与运算,用一个变量代替
    if(!that.global){
        //that = eval(that + 'g');
        var temp = /^\/(.+)\/$/.exec(that+'')[1];
        that = new RegExp(temp,'g');
    }
    var res = that.exec(str);
    var ary = [];
    while(res){
        ary.push(res);
        res = that.exec(str);
    }
    return ary;
}