Last active
April 1, 2025 17:27
-
-
Save mohasinkr/f0eae899b488fded6d46717b3126638a to your computer and use it in GitHub Desktop.
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
| /** | |
| * Splits a sentence into two parts based on a focus keyword. | |
| * Handles case-insensitivity and edge cases gracefully. | |
| * | |
| * @param sentence - The full sentence. | |
| * @param focusKeyword - The keyword to highlight. | |
| * @returns An object containing `firstWord` and `lastWord` around the keyword. | |
| * | |
| * 🔹 **Use Case: WordPress ACF (Advanced Custom Fields)** | |
| * - This function can be used in a **React/Next.js frontend** to dynamically highlight keywords | |
| * fetched from WordPress ACF fields. | |
| * - Example: Highlight a focus keyword in dynamic **page titles** or **section headers**. | |
| * - Works well with ACF fields like **heading, subheading, CTA texts, SEO meta descriptions, etc.** | |
| * | |
| * 🔹 **Example Usage with ACF in Next.js** | |
| * ```ts | |
| * import { focusKeywordSplitter } from "@/lib/focusKeywordSplitter"; | |
| * | |
| * const title = "Boost Your SEO with AI Tools"; | |
| * const focusWord = "SEO"; // From ACF field | |
| * const { firstWord, lastWord } = focusKeywordSplitter(title, focusWord); | |
| * | |
| * return ( | |
| * <h1> | |
| * {firstWord} <span className="text-primary">{focusWord}</span> {lastWord} | |
| * </h1> | |
| * ); | |
| * ``` | |
| */ | |
| export const focusKeywordSplitter = (sentence: string, focusKeyword: string) => { | |
| if (!sentence || !focusKeyword) { | |
| return { firstWord: "", lastWord: "" }; | |
| } | |
| const sentenceLower = sentence.toLowerCase(); | |
| const keywordLower = focusKeyword.toLowerCase(); | |
| const startIndex = sentenceLower.indexOf(keywordLower); | |
| if (startIndex === -1) { | |
| return { firstWord: sentence, lastWord: "" }; | |
| } | |
| const endIndex = startIndex + focusKeyword.length; | |
| return { | |
| firstWord: sentence.substring(0, startIndex).trim(), | |
| lastWord: sentence.substring(endIndex).trim(), | |
| }; | |
| }; | |
| // Example Usage: | |
| const result = focusKeywordSplitter("Boost Your SEO with AI Tools", "SEO"); | |
| console.log(result); // { firstWord: "Boost Your", lastWord: "with AI Tools" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment