Last active
April 3, 2024 14:50
-
-
Save edivados/0b24fd7e876d1940fd273361a31ffe1c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!