Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: iansinnott/react-string-replace
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: DerGoogler/react-string-replace
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
Able to merge. These branches can be automatically merged.
  • 1 commit
  • 2 files changed
  • 1 contributor

Commits on Sep 23, 2022

  1. Add ReactStringReplace Component

    Der_Googler committed Sep 23, 2022

    Verified

    This commit was signed with the committer’s verified signature.
    ljharb Jordan Harband
    Copy the full SHA
    11f8060 View commit details
Showing with 35 additions and 6 deletions.
  1. +22 −5 index.d.ts
  2. +13 −1 index.js
27 changes: 22 additions & 5 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
declare module 'react-string-replace' {
declare module "react-string-replace" {
function reactStringReplace(
text?: string | React.ReactNodeArray,
regex?: string | RegExp,
text?: string | React.ReactNode[],
regex?: string | RegExp,
cb?: (match: string, index: number, offset: number) => React.ReactNode
): React.ReactNodeArray;
): React.ReactNode[];

export default reactStringReplace;
type ReactStringReplaceRules = {
search: string | RegExp;
onMatch: (match: string, index: number) => React.ReactNode;
}[];

type ReactStringReplaceProps = {
rules: ReactStringReplaceRules;
children: string | React.ReactNode[];
};

function ReactStringReplace(props: ReactStringReplaceProps): JSX.Element;

export {
reactStringReplace,
ReactStringReplace,
ReactStringReplaceProps,
ReactStringReplaceRules,
};
}
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -85,10 +85,22 @@ function replaceString(str, match, fn) {
return result;
}

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

return flatten(source.map(function(x) {
return isString(x) ? replaceString(x, match, fn) : x;
}));
};

function ReactStringReplace(props) {
let tmp = [props.children];

props.rules.forEach(({ search, onMatch }) => {
tmp = reactStringReplace(tmp, search, onMatch);
});

return <>{tmp}</>;
};

module.exports = { reactStringReplace, ReactStringReplace }