Skip to content

Instantly share code, notes, and snippets.

@premrajah
Created October 23, 2024 14:42
Show Gist options
  • Save premrajah/2e1bde102b8d4466dd66a44058e386d6 to your computer and use it in GitHub Desktop.
Save premrajah/2e1bde102b8d4466dd66a44058e386d6 to your computer and use it in GitHub Desktop.
React highlight text with Index
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