Created
October 23, 2024 14:42
-
-
Save premrajah/2e1bde102b8d4466dd66a44058e386d6 to your computer and use it in GitHub Desktop.
React highlight text with Index
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
import React from "react"; | |
export const highlightTextHelper = (input, searchTerm) => { | |
if (!input || !searchTerm) return <>{input}</>; | |
let textIndex = input.toLowerCase().indexOf(searchTerm.toLowerCase()); | |
if (textIndex !== -1) { | |
let startText = input.substring(0, textIndex); | |
let foundText = input.substring(textIndex, textIndex + searchTerm.length); | |
let endText = input.substring(textIndex + searchTerm.length); | |
return ( | |
<> | |
{startText} | |
<b style={{ color: "#000" }}>{foundText}</b> | |
{endText} | |
</> | |
); | |
} else { | |
return <>{input}</>; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment