string.prototype.matchall

Spec-compliant polyfill for String.prototype.matchAll

MIT 18 个版本
安装
npm install string.prototype.matchall
yarn add string.prototype.matchall
pnpm add string.prototype.matchall
bun add string.prototype.matchall
README

string.prototype.matchall Version Badge

github actions coverage License Downloads

npm badge

ES2020 spec-compliant shim for String.prototype.matchAll. Invoke its "shim" method to shim String.prototype.matchAll if it is unavailable or noncompliant.

This package implements the es-shim API interface. It works in an ES3-supported environment, and complies with the spec.

Most common usage:

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

const str = 'aabc';
const nonRegexStr = 'ab';
const globalRegex = /[ac]/g;
const nonGlobalRegex = /[bc]/i;

// non-regex arguments are coerced into a global regex
assert.deepEqual(
	[...matchAll(str, nonRegexStr)],
	[...matchAll(str, new RegExp(nonRegexStr, 'g'))]
);

assert.deepEqual([...matchAll(str, globalRegex)], [
	Object.assign(['a'], { index: 0, input: str, groups: undefined }),
	Object.assign(['a'], { index: 1, input: str, groups: undefined }),
	Object.assign(['c'], { index: 3, input: str, groups: undefined }),
]);

assert.throws(() => matchAll(str, nonGlobalRegex)); // non-global regexes throw

matchAll.shim(); // will be a no-op if not needed

// non-regex arguments are coerced into a global regex
assert.deepEqual(
	[...str.matchAll(nonRegexStr)],
	[...str.matchAll(new RegExp(nonRegexStr, 'g'))]
);

assert.deepEqual([...str.matchAll(globalRegex)], [
	Object.assign(['a'], { index: 0, input: str, groups: undefined }),
	Object.assign(['a'], { index: 1, input: str, groups: undefined }),
	Object.assign(['c'], { index: 3, input: str, groups: undefined }),
]);

assert.throws(() => matchAll(str, nonGlobalRegex)); // non-global regexes throw

Tests

Simply clone the repo, npm install, and run npm test

版本列表
4.0.12 2024-12-20
4.0.11 2024-03-20
4.0.10 2023-09-13
4.0.9 2023-08-29
4.0.8 2022-11-07
4.0.7 2022-03-19
4.0.6 2021-10-05
4.0.5 2021-05-25
4.0.4 2021-02-21
4.0.3 2020-11-20
4.0.2 2019-12-23
4.0.1 2019-12-13
4.0.0 2019-10-03
3.0.2 2019-10-02
3.0.1 2018-12-12
3.0.0 2018-06-01
2.0.0 2018-01-24
1.0.0 2017-09-28