How to find common words in two strings with TypeScript

1 Answer

0 votes
/*
    Normalize a string:
    - Convert letters to lowercase
    - Replace any non-letter with a space
    This ensures consistent word comparison.
*/
function normalize(text: string): string {
    let result: string = "";

    for (const ch of text) {
        if (/[a-zA-Z]/.test(ch)) {
            result += ch.toLowerCase();
        } else {
            result += " ";
        }
    }

    return result;
}

/*
    Extract words from a string.

    This function:
    - Normalizes the input
    - Splits on whitespace
    - Filters out empty entries
    - Returns a Set<string> for fast lookup and automatic duplicate removal
*/
function extractWords(text: string): Set<string> {
    const normalized: string = normalize(text);
    const parts: string[] = normalized.split(/\s+/);

    const words: Set<string> = new Set();
    for (const w of parts) {
        if (w.length > 0) {
            words.add(w);
        }
    }

    return words;
}

/*
    Find common words between two strings.

    This function:
    - Extracts words from both strings
    - Uses set intersection for efficiency
    - Returns a new Set<string> containing the common words
*/
function findCommonWords(a: string, b: string): Set<string> {
    const wordsA: Set<string> = extractWords(a);
    const wordsB: Set<string> = extractWords(b);

    const common: Set<string> = new Set();
    for (const w of wordsA) {
        if (wordsB.has(w)) {
            common.add(w);
        }
    }

    return common;
}

/*
    Main execution
*/
const s1: string = "The quick brown fox jumps over the lazy dog.";
const s2: string = "A lazy dog sleeps while the quick fox runs away.";

const common: Set<string> = findCommonWords(s1, s2);

console.log("Common words:");
for (const w of common) {
    console.log(w);
}



/*
run:

Common words:
the
quick
fox
lazy
dog

*/

 



answered Sep 11 by avibootz
...