diff --git a/index.d.ts b/index.d.ts index 4141473..e3c6eb2 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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, + }; } diff --git a/index.js b/index.js index f34f074..1316e5f 100644 --- a/index.js +++ b/index.js @@ -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 }