diff --git a/index.js b/index.js index f34f074..64a72f8 100644 --- a/index.js +++ b/index.js @@ -78,7 +78,7 @@ function replaceString(str, match, fn) { curCharLen = result[i].length; curCharStart += result[i - 1].length; - result[i] = fn(result[i], i, curCharStart); + result[i] = fn(result[i], (i - 1) / 2, curCharStart); curCharStart += curCharLen; } diff --git a/test.js b/test.js index 761d43d..ab22e88 100644 --- a/test.js +++ b/test.js @@ -170,3 +170,14 @@ test("Avoids undefined values due to regex", (t) => { replaceString(string, /(hey)|(you)/, x => x); }); }); + +test("Indexes start at 0 and are contiguous", t => { + const string = 'Hello there general Kenobi'; + const re = /(\w+)/; + + let expectedIndex = 0; + replaceString(string, re, (match, index) => { + t.deepEqual(expectedIndex, index); + expectedIndex++; + }); +});