Skip to content

Commit 0cc751d

Browse files
authored
Merge pull request #9 from pejrak/master
Added character start to fn call arguments per issue #8
2 parents ce2fd67 + a388a8f commit 0cc751d

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

index.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ var flatten = require('lodash.flatten');
2828
* @return {array}
2929
*/
3030
function replaceString(str, match, fn) {
31+
var curCharStart = 0;
32+
var curCharLen = 0;
33+
3134
if (str === '') {
3235
return str;
3336
} else if (!str || !isString(str)) {
@@ -44,7 +47,10 @@ function replaceString(str, match, fn) {
4447

4548
// Apply fn to all odd elements
4649
for (var i = 1, length = result.length; i < length; i += 2) {
47-
result[i] = fn(result[i], i);
50+
curCharLen = result[i].length;
51+
curCharStart += result[i - 1].length;
52+
result[i] = fn(result[i], i, curCharStart);
53+
curCharStart += curCharLen;
4854
}
4955

5056
return result;

readme.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,10 +135,10 @@ reactStringReplace('hey hey you', /(hey)/g, () => <span>hey</span>);
135135

136136
Type: `function`
137137

138-
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.
138+
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.
139139

140140
```js
141-
const func = (match, index) => <span key={index}>{match}</span>;
141+
const func = (match, index, offset) => <span key={index}>{match}</span>;
142142
reactStringReplace('hey hey you', /(hey)/g, func);
143143
```
144144

test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ test('Returns an array', t => {
1111
t.true(Array.isArray(replaceString('blah', 'blah', x => x)));
1212
});
1313

14+
test('Returns correct character offsets', t => {
15+
const correctOffsets = [6, 17];
16+
const charOffsets = [];
17+
18+
replaceString('Hey there, stranger', 'er', (m, i, o) => charOffsets.push(o));
19+
t.deepEqual(charOffsets, correctOffsets);
20+
});
21+
1422
test('Works with matching groups', t => {
1523
t.deepEqual(
1624
replaceString('hey there', /(hey)/g, x => ({ worked: x })),

0 commit comments

Comments
 (0)