寻找JavaScript中String.matchAll的低版本兼容替代方案
matchAll 低版本环境替代实现方案
String.prototype.matchAll 是 ES2020 新增的字符串 API,老旧运行环境(如IE、12.0版本以下的Node.js、旧版移动端浏览器)均不支持该方法,可选择以下兼容方案落地:
- 方案1:
RegExp.exec循环实现(兼容性最优,支持ES3及以上所有环境)
带g全局修饰符的正则执行exec方法时,会自动更新正则实例的lastIndex属性,匹配到结果时返回完整的匹配信息(含捕获组、匹配位置、原字符串等,和matchAll返回的单条结果结构完全一致),匹配失败返回null,循环遍历即可拿到所有匹配结果:
const regexp = /t(e)(st(\d?))/g; const str = 'test1test2'; const array = []; let match; // 每次执行exec都会自动向后匹配,直到返回null为止 while ((match = regexp.exec(str)) !== null) { array.push(match); }
最终得到的array和[...str.matchAll(regexp)]的结构完全一致。
- 方案2:封装全局polyfill,无侵入兼容原生写法
如果不想修改原有业务代码,可直接在项目入口引入以下polyfill代码,之后即可正常使用原生matchAll的调用方式:
if (typeof String.prototype.matchAll === 'undefined') { String.prototype.matchAll = function (regexp) { // 参数校验和原生逻辑保持一致 if (!(regexp instanceof RegExp)) { throw new TypeError('First argument to String.prototype.matchAll must be a RegExp'); } if (!regexp.global) { throw new TypeError('String.prototype.matchAll called with a non-global RegExp argument'); } const result = []; let match; // 重置lastIndex,避免之前的执行结果干扰当前匹配 regexp.lastIndex = 0; while ((match = regexp.exec(this)) !== null) { result.push(match); } // 兼容可迭代接口,支持扩展运算符、for...of遍历 return result[Symbol.iterator] ? result : result.values(); }; }
引入后原代码const array = [...str.matchAll(regexp)]可直接运行,无需修改。
- 方案3:无需捕获组时可直接使用
match方法
如果你的业务场景只需要获取所有匹配的完整字符串,不需要拿到每个匹配的捕获组信息,直接使用带g修饰符的match方法即可:
const regexp = /t(e)(st(\d?))/g; const str = 'test1test2'; const array = str.match(regexp); // 输出结果为 ['test1', 'test2']
内容的提问来源于stack exchange,提问作者kfir
相关产品推荐
相关产品推荐

