Skip to content

Feat: Add count parameter to match only the first 'n' items #91

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

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ declare module "react-string-replace" {
function reactStringReplace(
text?: string | React.ReactNode[],
regex?: string | RegExp,
cb?: (match: string, index: number, offset: number) => React.ReactNode
cb?: (match: string, index: number, offset: number) => React.ReactNode,
count?: number
): React.ReactNode[];

export default reactStringReplace;
Expand Down
32 changes: 26 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ var flatten = function (array) {
* @param {function} fn
* @return {array}
*/
function replaceString(str, match, fn) {
function replaceString(str, match, fn, count = null) {
var curCharStart = 0;
var curCharLen = 0;

Expand All @@ -70,6 +70,11 @@ function replaceString(str, match, fn) {

// Apply fn to all odd elements
for (var i = 1, length = result.length; i < length; i += 2) {

if (Number.isInteger(count) && (count * 2 < i || count < 1)) {
break;
}

/** @see {@link https://github.com/iansinnott/react-string-replace/issues/74} */
if (result[i] === undefined || result[i - 1] === undefined) {
console.warn('reactStringReplace: Encountered undefined value during string replacement. Your RegExp may not be working the way you expect.');
Expand All @@ -85,10 +90,25 @@ function replaceString(str, match, fn) {
return result;
}

module.exports = function reactStringReplace(source, match, fn) {
module.exports = function reactStringReplace(source, match, fn, count = null) {
if (!Array.isArray(source)) source = [source];

return flatten(source.map(function(x) {
return isString(x) ? replaceString(x, match, fn) : x;
}));
};
return flatten(
source.map(function (x) {
let ret;
if (isString(x)) {
if (Number.isInteger(count) && count > 0) {
ret = replaceString(x, match, fn, count);
count -= (
x.match(new RegExp("(" + escapeRegExp(match) + ")", "gi")) || []
).length
} else {
ret = replaceString(x, match, fn, count);
}
} else {
ret = x;
}
return ret;
}),
);
}
14 changes: 13 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ I wanted an easy way to do string replacement similar to `String.prototype.repla

## API

### reactStringReplace(string, match, replacementFunction)
### reactStringReplace(string, match, replacementFunction, count)

#### string

Expand Down Expand Up @@ -163,6 +163,18 @@ const replacementFunction = (match, index, offset) => <span key={index}>{match}<
reactStringReplace('hey hey you', /(hey)/g, replacementFunction);
```

#### count

Type: `number`

The number of substitutions to perform - for example if `count` is 1, then only the first occurrence of the string will be replaced.

Example: Replace first occurrence of `'hey'` with `<span>hey</span>`

```js
reactStringReplace('hey hey you', 'hey', () => <span>hey</span>, 1)
```

## API Stability

With v1.0.0 the API is considered stable and should be considered production ready. Pull requests are still welcome but there is currently no intent to make changes to this lib other than bug fixes (please submit an issue if you find something!).
Expand Down
15 changes: 15 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable import/no-extraneous-dependencies */
import test from 'ava';
import replaceString from './';
import reactStringReplace from '.';

test("Doesn't throw if not given invalid input", t => {
t.notThrows(() => replaceString());
Expand Down Expand Up @@ -170,3 +171,17 @@ test("Avoids undefined values due to regex", (t) => {
replaceString(string, /(hey)|(you)/, x => x);
});
});

test("Fixed number of string replacements", (t) => {
const string = `Test hey test hey test`;
const replacedContent = reactStringReplace(string, 'hey', match => {
return 'lo';
},1);
t.deepEqual(replacedContent, [
'Test ',
'lo',
' test ',
'hey',
' test'
])
})
Loading