Skip to content

Added character start to fn call arguments per issue #8 #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 22, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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