Last active
November 7, 2021 18:33
-
-
Save douglasjunior/4277ed132cd9d1cb92778d621efc6ea5 to your computer and use it in GitHub Desktop.
Função para destacar partes de um texto usando React
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
/** | |
* 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