首页 > 解决方案 > 如何使用 string.prototype.matchall polyfill?

问题描述

我希望String.prototype.matchAll()方法也可以在边缘浏览器中工作。于是想到了使用“string.prototype.matchall”npmjs 包

我已经安装了这个包并main.js像这样导入到我的文件中

import 'string.prototype.matchall';

我必须在其他文件中使用这种方法,Input.js.所以我使用如下

const matchAll = require('string.prototype.matchall');

在我实际匹配字符串的方法中,如下

replace = (original_string) => {
  const regex_pattern = /\\d+@*)]/g;
  const matchAll = require('string.prototype.matchall'); 
  const matches = original_string.matchAll(regex_pattern);
  return matches;
}

matchAll变量未使用。如何使用这个string.prototype.matchall polyfill。有人可以帮我解决这个问题吗?谢谢。

标签: javascriptshim

解决方案


我用过这个,对我有用。循环遍历全局标记模式的匹配就可以了。如果您在使用它时遇到任何问题,请告诉我,我很乐意为您提供帮助。

function matchAll(pattern,haystack){
    var regex = new RegExp(pattern,"g")
    var matches = [];
    
    var match_result = haystack.match(regex);
    
    for (let index in match_result){
        var item = match_result[index];
        matches[index] = item.match(new RegExp(pattern)); 
    }
    return matches;
}

推荐阅读