type CustomComponentFunction = (
tagName: string,
content: string,
) => React.ReactNode;
const parseTextWithComponents = (
text: string,
getCustomComponentFunction: CustomComponentFunction,
): React.ReactNode => {
const customComponentRegex = /<(\w+)>(.*?)<\/\1>/g;
const components: React.ReactNode[] = [];
let lastIndex = 0;
let match = customComponentRegex.exec(text);
while (match !== null) {
const fullMatch = match[0];
const tagName = match[1];
const content = match[2];
const beforeCustomComponent = text.slice(lastIndex, match.index);
const customComponent = getCustomComponentFunction(tagName, content);
components.push(beforeCustomComponent);
components.push(customComponent);
lastIndex = match.index + fullMatch.length;
match = customComponentRegex.exec(text);
}
if (lastIndex < text.length) {
const remainingText = text.slice(lastIndex);
components.push(remainingText);
}
return components;
};
Leave a comment