Last active
March 18, 2018 23:05
-
-
Save dangreenisrael/ad1ee2785f934f4df3b80cf45d6afac5 to your computer and use it in GitHub Desktop.
JavaScript function to get all capture groups for a global regex.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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