Skip to content

Instantly share code, notes, and snippets.

@dangreenisrael
Last active March 18, 2018 23:05
Show Gist options
  • Save dangreenisrael/ad1ee2785f934f4df3b80cf45d6afac5 to your computer and use it in GitHub Desktop.
Save dangreenisrael/ad1ee2785f934f4df3b80cf45d6afac5 to your computer and use it in GitHub Desktop.
JavaScript function to get all capture groups for a global regex.
const getRegexCaptures = (regex, string) => {
const getMatches = (cursor, results = []) => {
const exp = regex.exec(string);
if (!exp) {
return results;
}
return getMatches(exp, [...results, exp[1]]);
};
return getMatches();
};
// Test case
const getRelativeImportPaths = fileContent => {
const regex = /from '(.*?)'/g;
return getRegexCaptures(regex, fileContent);
};
const testData = `
import {Foo} from '../../Foo';
import Bar from '../Bar';
`;
expect(getRelativeImportPaths(testData)).toEqual(['../../Foo', '../Bar']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment