diff --git a/index.js b/index.js index e4a0de1..6ecabdd 100644 --- a/index.js +++ b/index.js @@ -28,6 +28,9 @@ var flatten = require('lodash.flatten'); * @return {array} */ function replaceString(str, match, fn) { + var curCharStart = 0; + var curCharLen = 0; + if (str === '') { return str; } else if (!str || !isString(str)) { @@ -44,7 +47,10 @@ function replaceString(str, match, fn) { // Apply fn to all odd elements for (var i = 1, length = result.length; i < length; i += 2) { - result[i] = fn(result[i], i); + curCharLen = result[i].length; + curCharStart += result[i - 1].length; + result[i] = fn(result[i], i, curCharStart); + curCharStart += curCharLen; } return result; diff --git a/readme.md b/readme.md index fbbd62a..b8b6f0b 100644 --- a/readme.md +++ b/readme.md @@ -135,10 +135,10 @@ reactStringReplace('hey hey you', /(hey)/g, () => hey); Type: `function` -The replacer function to run each time `match` is found. This function will be patched the matching string and an index which can be used for adding keys to replacement components if necessary. +The replacer function to run each time `match` is found. This function will be patched the matching string and an `index` which can be used for adding keys to replacement components if necessary. Character `offset` identifies the position of match start in the provided text. ```js -const func = (match, index) => {match}; +const func = (match, index, offset) => {match}; reactStringReplace('hey hey you', /(hey)/g, func); ``` diff --git a/test.js b/test.js index c393e90..900efb1 100644 --- a/test.js +++ b/test.js @@ -11,6 +11,14 @@ test('Returns an array', t => { t.true(Array.isArray(replaceString('blah', 'blah', x => x))); }); +test('Returns correct character offsets', t => { + const correctOffsets = [6, 17]; + const charOffsets = []; + + replaceString('Hey there, stranger', 'er', (m, i, o) => charOffsets.push(o)); + t.deepEqual(charOffsets, correctOffsets); +}); + test('Works with matching groups', t => { t.deepEqual( replaceString('hey there', /(hey)/g, x => ({ worked: x })),