Skip to content
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
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
Expand Up @@ -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 }