Skip to content

Instantly share code, notes, and snippets.

@douglasjunior
Last active November 7, 2021 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglasjunior/4277ed132cd9d1cb92778d621efc6ea5 to your computer and use it in GitHub Desktop.
Save douglasjunior/4277ed132cd9d1cb92778d621efc6ea5 to your computer and use it in GitHub Desktop.
Função para destacar partes de um texto usando React
/**
* Função para destacar partes de um texto.
* Exemplo de uso:
* <span>
* {applyHighlight(text, highlight, { backgroundColor: 'yellow' })}
* </span>
*
* @param {string} text Texto
* @param {string|RegExp} highlight Parte do texto a ser destacada
* @param {object} options Propriedades do <span> para as partes destacadas
* @return {Array} Array de elementos React
*/
function applyHighlight(text, highlight, options = {}) {
if (text && highlight) {
const regex = highlight instanceof RegExp ? highlight : new RegExp(highlight, "gmi");
let match;
let lastIndex = 0;
const textParts = [];
while ((match = regex.exec(text))) {
const start = match.index;
const end = regex.lastIndex;
textParts.push(
<span key={'text-' + lastIndex}>
{text.substring(lastIndex, start)}
</span>
);
textParts.push(
<span {...options} key={'high-' + start} >
{text.substring(start, end)}
</span>
);
lastIndex = end;
}
if (!textParts.length) return text;
textParts.push(
<span key={'text-' + lastIndex}>
{text.substring(lastIndex, text.lastIndex)}
</span>
);
return textParts;
}
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment