Skip to content

Instantly share code, notes, and snippets.

@edivados
Last active April 3, 2024 14:50
Show Gist options
  • Save edivados/0b24fd7e876d1940fd273361a31ffe1c to your computer and use it in GitHub Desktop.
Save edivados/0b24fd7e876d1940fd273361a31ffe1c to your computer and use it in GitHub Desktop.
function regReplaceWithComponent(
text: string,
exp: RegExp,
fn: (match: string, index: number) => JSXElement
) {
const matches = Array.from(text.matchAll(exp));
const items: JSXElement[] = [];
for (let index = 0; index < matches.length; index++) {
const match = matches[index];
const prevMatch = index ? matches[index - 1] : undefined;
const offset = prevMatch ? prevMatch.index! + prevMatch[0].length : 0;
items.push(text.slice(offset, match.index));
items.push(fn(match[0], index));
const isLastMatch = index === matches.length - 1;
const hasTextAfterLastMatch = match.index! + match[0].length < text.length;
if (isLastMatch && hasTextAfterLastMatch) {
items.push(text.slice(match.index! + match[0].length));
}
}
return items.length ? items : text;
}
@joshuaiz
Copy link

joshuaiz commented Apr 3, 2024

Hello. I think this is exactly what I need but struggling to get it working.

What should the third argument for the fn be? For example if I have a component <ProductTiles /> how should that be passed in?

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment