Skip to content

Commit

Permalink
Merge pull request #9 from pejrak/master
Browse files Browse the repository at this point in the history
Added character start to fn call arguments per issue #8
  • Loading branch information
iansinnott authored Nov 22, 2016
2 parents ce2fd67 + a388a8f commit 0cc751d
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
8 changes: 7 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,10 @@ reactStringReplace('hey hey you', /(hey)/g, () => <span>hey</span>);

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) => <span key={index}>{match}</span>;
const func = (match, index, offset) => <span key={index}>{match}</span>;
reactStringReplace('hey hey you', /(hey)/g, func);
```

Expand Down
8 changes: 8 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })),
Expand Down

0 comments on commit 0cc751d

Please sign in to comment.