Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

How to remove duplicate words from free‑text in TypeScript

1 Answer

0 votes
/**
 * splitWords
 *
 * Splits free text into words using a Unicode-aware regex.
 *
 * JavaScript/TypeScript supports Unicode property escapes with the "u" flag:
 *
 *   \p{Letter}   → any Unicode letter
 *
 * So we split on ANY sequence of NON-letters:
 *
 *   /[^\p{Letter}]+/u
 *
 * This is fully Unicode-aware and works in modern JS engines.
 */
function splitWords(text: string): string[] {
  const trimmed: string = text.trim();

  // Split on any sequence of non-letter characters
  const parts: string[] = trimmed.split(/[^\p{Letter}]+/u);

  return parts;
}

/**
 * removeDuplicateWords
 *
 * Removes duplicate words while preserving:
 *   - original order
 *   - original casing of first occurrence
 *   - case-insensitive comparison
 *
 * Uses Set for O(1) average lookup time.
 */
function removeDuplicateWords(text: string): string {
  const words: string[] = splitWords(text);

  const seen: Set<string> = new Set<string>();
  const unique: string[] = [];

  for (const word of words) {
    if (word === "") continue;

    const key: string = word.toLowerCase(); // Unicode-aware lowercase

    if (!seen.has(key)) {
      seen.add(key);
      unique.push(word); // preserve original casing
    }
  }

  // Reassemble into a space-separated string
  const result: string = unique.join(" ");
  
  return result;
}

// ------------------------------------------------------------
// Program entry point
// ------------------------------------------------------------
const input: string =
  "Hello, hello! This is a test. A TEST, hello universe...   " +
  "UNIVERSE! Hello; ***  Is Anybody There?";

const output: string = removeDuplicateWords(input);

console.log(output);



/*
run:

Hello This is a test universe Anybody There

*/

 



answered 6 days ago by avibootz
...