Skip to content

Commit 049db6f

Browse files
committed
fix!: correct index value in callback (BREAKING CHANGE)
The index parameter passed to the replacement callback now returns logical match index (0, 1, 2, 3...) instead of internal array index (1, 3, 5, 7...). This is more intuitive and useful for React key props. BREAKING CHANGE: The second parameter to the replacement callback now starts at 0 and increments by 1, rather than starting at 1 and incrementing by 2. Fixes #32 Closes #92
1 parent 40a4bf9 commit 049db6f

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ function replaceString(str, match, fn, count = null) {
8383

8484
curCharLen = result[i].length;
8585
curCharStart += result[i - 1].length;
86-
result[i] = fn(result[i], i, curCharStart);
86+
result[i] = fn(result[i], (i - 1) / 2, curCharStart);
8787
curCharStart += curCharLen;
8888
}
8989

test.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,9 @@ test("Avoids undefined values due to regex", (t) => {
172172
});
173173
});
174174

175-
test("Fixed number of string replacements", (t) => {
175+
test("Fixed number of string replacements", (t) => {
176176
const string = `Test hey test hey test`;
177-
const replacedContent = reactStringReplace(string, 'hey', match => {
177+
const replacedContent = reactStringReplace(string, 'hey', match => {
178178
return 'lo';
179179
},1);
180180
t.deepEqual(replacedContent, [
@@ -184,4 +184,15 @@ test("Fixed number of string replacements", (t) => {
184184
'hey',
185185
' test'
186186
])
187-
})
187+
});
188+
189+
test("Indexes start at 0 and are contiguous", t => {
190+
const string = 'Hello there general Kenobi';
191+
const re = /(\w+)/;
192+
193+
let expectedIndex = 0;
194+
replaceString(string, re, (match, index) => {
195+
t.deepEqual(expectedIndex, index);
196+
expectedIndex++;
197+
});
198+
});

0 commit comments

Comments
 (0)