我希望String.prototype.matchAll()
方法也能在边缘浏览器中工作。于是想到使用“string.prototype.matchall”npmjs包
我已经安装了这个包并main.js
像这样导入到我的文件中
import 'string.prototype.matchall';
Run Code Online (Sandbox Code Playgroud)
我必须在其他文件中使用这种方法,Input.js.
所以我使用如下
const matchAll = require('string.prototype.matchall');
Run Code Online (Sandbox Code Playgroud)
在我实际匹配字符串的方法中
replace = (original_string) => {
const regex_pattern = /\\d+@*)]/g;
const matchAll = require('string.prototype.matchall');
const matches = original_string.matchAll(regex_pattern);
return matches;
}
Run Code Online (Sandbox Code Playgroud)
但matchAll
变量未使用。我如何使用这个string.prototype.matchall polyfill。有人可以帮我解决这个问题吗?谢谢。
因为包实现了es-shim API,所以您应该调用该shim()
方法...
require('foo').shim
orrequire('foo/shim')
是一个函数,在调用时将调用getPolyfill
,如果 polyfill 与内置值不匹配,则将其安装到全局环境中。
这将让您使用String.prototype.matchAll()
.
const matchAll = require('string.prototype.matchall')
matchAll.shim()
const matches = original_string.matchAll(regex_pattern)
Run Code Online (Sandbox Code Playgroud)
否则,您可以单独使用它
require('foo')
是符合规范的 JS 或本机函数。但是,如果函数的行为取决于接收器(“this”值),则此函数的第一个参数将用作该接收器。该包应在其自述文件中指明是否属于这种情况
const matchAll = require('string.prototype.matchall')
const matches = matchAll(original_string, regex_pattern)
Run Code Online (Sandbox Code Playgroud)
要使用 ES6 模块导入,您可以在脚本顶部使用类似的内容(不在您的replace
函数中)
import shim from 'string.prototype.matchall/shim'
shim()
Run Code Online (Sandbox Code Playgroud)
我用过这个,对我有用。循环遍历全局标记模式的匹配就成功了。如果您在使用它时遇到任何问题,请告诉我,我将很乐意为您提供帮助。
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;
}
Run Code Online (Sandbox Code Playgroud)