How to use the string.prototype.matchall polyfill?

半城伤御伤魂 提交于 2020-12-12 05:16:14

问题


I want String.prototype.matchAll() method to be working in edge browser as well. So thought of using the "string.prototype.matchall" npmjs package

I have installed this package and imported in my main.js file like so

import 'string.prototype.matchall';

I have to use this method in other file say Input.js. so I use like below

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

And in the method where this I actually match the strings is below

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

but matchAll variable is unused. How do I use this string.prototype.matchall polyfill. Could someone help me with this? Thanks.


回答1:


Because the package implements the es-shim API, you should call the shim() method...

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.

This will let you use String.prototype.matchAll().

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

const matches = original_string.matchAll(regex_pattern)

Otherwise, you can use it stand-alone

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)

To use an ES6 module import, you would use something like this at the top of your script (not within your replace function)

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



回答2:


I used this, works for me. Looping through the matches of global flagged pattern did the trick. Let me know if you have any issue using it, I will be glad to help.

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


来源:https://stackoverflow.com/questions/58003217/how-to-use-the-string-prototype-matchall-polyfill

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!