How To Use The String.prototype.matchall Polyfill?
Solution 1:
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.
functionmatchAll(pattern,haystack){
var regex = newRegExp(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(newRegExp(pattern));
}
return matches;
}
Solution 2:
Because the package implements the es-shim API, you should call the shim()
method...
require('foo').shim
orrequire('foo/shim')
is a function that when invoked, will callgetPolyfill
, 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()
Solution 3:
You can also use the exec
RegExp method.
functionmatchAll(re, str) {
let match
const matches = []
while (match = re.exec(str)) {
// add all matched groups
matches.push(...match.slice(1))
}
return matches
}
Post a Comment for "How To Use The String.prototype.matchall Polyfill?"