react-wrap-text
Version:
A simple utility to wrap matching substrings in React with custom jsx components
34 lines (33 loc) • 851 B
JavaScript
// src/wrapMatches.ts
function wrapMatchesInText(input, target, render) {
if (!target)
return [input];
const parts = input.split(target);
const result = [];
parts.forEach((part, index) => {
result.push(part);
if (index < parts.length - 1) {
result.push(render(target, index));
}
});
return result;
}
function wrapMultipleMatchesInText(input, matches) {
return matches.reduce((current, { target, render }) => {
return current.flatMap((node, outerIndex) => {
if (typeof node === "string") {
return wrapMatchesInText(
node,
target,
(match, i) => render(match, outerIndex * 1e3 + i)
// key strategy
);
}
return [node];
});
}, typeof input === "string" ? [input] : input);
}
export {
wrapMatchesInText,
wrapMultipleMatchesInText
};