const escapeRegExp = (inputString: string) =>
inputString.replace(/\[|\{}()[]^$+*?.]/g, '\$&').replace(/-/g, '\x2d');
const defaultGetHighlightRegex = (highlightValue: string) => new RegExp(escapeRegExp(highlightValue), 'gi');
export const highlight = (text: string, highlightValue: string, customGetHighlightRegex: any) => {
const getHighlightRegex = customGetHighlightRegex || defaultGetHighlightRegex
const highlightRegex = getHighlightRegex(highlightValue)
const matches = text.match(highlightRegex) || []
const remaining = text.split(highlightRegex).filter((w) => matches.indexOf(w) === -1)
return remaining.reduce(
(acc, nonMatch, nonMatchIndex) => [
...acc,
nonMatch || null,
matches[nonMatchIndex] ? <strong key={`${text}${nonMatchIndex}`}>{matches[nonMatchIndex]}</strong> : null,
],
[]
)
}
<span>{highlight("doan", "do", undefined)}</span>