Skip to content

Commit 8695ee5

Browse files
committed
fix: handle matched and captured text
1 parent ff2e27f commit 8695ee5

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

electron/common/string/__tests__/string-utils.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ describe('string-utils', () => {
112112
describe('#sliceStart', () => {
113113
test('when the pattern is found at the start of the string then returns the original string, the matched pattern, and the remaining string', () => {
114114
const text = 'foo bar baz';
115-
const regex = /^foo/;
115+
const regex = /^(foo)/;
116116

117117
const result = sliceStart({ text, regex });
118118

@@ -125,7 +125,7 @@ describe('string-utils', () => {
125125

126126
test('when the pattern is not found at the start of the string then returns the original string, undefined for the matched pattern, and the original string for the remaining string', () => {
127127
const text = 'foo bar baz';
128-
const regex = /^bar/;
128+
const regex = /^(bar)/;
129129

130130
const result = sliceStart({ text, regex });
131131

electron/common/string/string.utils.ts

+13-4
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,17 @@ export function sliceStart(options: {
2929
/**
3030
* The pattern to match at the start of the input text.
3131
* Must include the ^ anchor to match the start of the string.
32+
* Must include one capturing group, which will be the returned matched text.
33+
*
34+
* Examples:
35+
* Good: /^(.+)/ One capturing group and ^ anchor
36+
* Bad: /^.+/ Missing capturing group
37+
* Bad: /(.+)/ Missing ^ anchor
3238
*/
3339
regex: RegExp;
3440
}): {
3541
/**
36-
* The string that matched the pattern at the start of the input text.
42+
* The first captured group matched by the pattern in the input text.
3743
*/
3844
match?: string;
3945
/**
@@ -52,12 +58,15 @@ export function sliceStart(options: {
5258
const matchResult = text.match(regex);
5359

5460
if (matchResult) {
55-
const [match] = matchResult;
61+
// The matched text is everything the regex pattern matched,
62+
// which may be more than what the capturing groups matched.
63+
// The captured text is only what was in the first captured group.
64+
const [matchedText, capturedText] = matchResult;
5665
const original = text;
57-
const remaining = text.slice(match.length);
66+
const remaining = text.slice(matchedText.length);
5867

5968
return {
60-
match,
69+
match: capturedText,
6170
original,
6271
remaining,
6372
};

0 commit comments

Comments
 (0)