-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { isEmpty } from 'lodash/fp'; | ||
|
||
export default (targetString, regExpString) => { | ||
const regExp = new RegExp(regExpString, 'g'); | ||
|
||
let matches = []; | ||
|
||
let execMatch; | ||
while ((execMatch = regExp.exec(targetString))) { | ||
const [match, group = null] = execMatch; | ||
|
||
matches.push({ match, group }); | ||
} | ||
|
||
return !isEmpty(matches) ? matches : null; | ||
}; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import matchAll from './matchAll'; | ||
|
||
describe('matchAll', () => { | ||
it('when called with regular expression containing multiple capturing groups and string that is matching, returns matches', () => { | ||
const actual = matchAll( | ||
'some-string-{containing}-some-{things-to-be-matched}', | ||
/{([^}]*)}/, | ||
); | ||
|
||
expect(actual).toEqual([ | ||
{ match: '{containing}', group: 'containing' }, | ||
{ match: '{things-to-be-matched}', group: 'things-to-be-matched' }, | ||
]); | ||
}); | ||
|
||
it('when called with regular expression containing single capturing group and string that is matching, returns matches', () => { | ||
const actual = matchAll('some-string-{containing}', /{([^}]*)}/); | ||
|
||
expect(actual).toEqual([{ match: '{containing}', group: 'containing' }]); | ||
}); | ||
|
||
it('when called with regular expression with no capturing group and string that is matching, returns matches', () => { | ||
const actual = matchAll('some', /./); | ||
|
||
expect(actual).toEqual([ | ||
{ match: 's', group: null }, | ||
{ match: 'o', group: null }, | ||
{ match: 'm', group: null }, | ||
{ match: 'e', group: null }, | ||
]); | ||
}); | ||
|
||
it('when called with regular expression and string that is not matching, returns null', () => { | ||
const actual = matchAll('irrelevant', /{([^}]*)}/); | ||
|
||
expect(actual).toBe(null); | ||
}); | ||
}); |