如何使用 string.prototype.matchall polyfill?

How to use the string.prototype.matchall polyfill?

我希望 String.prototype.matchAll() 方法也能在边缘浏览器中工作。于是想到用the "string.prototype.matchall" npmjs package

我已经安装了这个包并像这样导入到我的 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。有人可以帮我吗?谢谢。

因为包实现了es-shim API,你应该调用shim()方法...

require('foo').shim or require('foo/shim') is a function that when invoked, will call getPolyfill, and if the polyfill doesn’t match the built-in value, will install it into the global environment.

这将使您可以使用 String.prototype.matchAll()

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

const matches = original_string.matchAll(regex_pattern)

否则,您可以单独使用它

require('foo') is a spec-compliant JS or native function. However, if the function’s behavior depends on a receiver (a “this” value), then the first argument to this function will be used as that receiver. The package should indicate if this is the case in its README

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

const matches = matchAll(original_string, regex_pattern)

要使用 ES6 模块导入,您可以在脚本顶部使用类似的内容(不是 在您的 replace 函数中)

import shim from 'string.prototype.matchall/shim'
shim()

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

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;
}

您也可以使用 exec RegExp 方法。

function matchAll(re, str) {
  let match
  const matches = []

  while (match = re.exec(str)) {
    // add all matched groups
    matches.push(...match.slice(1))
  }

  return matches
}