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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

How to find common words in two strings with JavaScript

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) {
    let result = "";

    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 for fast lookup and automatic duplicate removal
*/
function extractWords(text) {
    const normalized = normalize(text);
    const parts = normalized.split(/\s+/);

    const words = 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 containing the common words
*/
function findCommonWords(a, b) {
    const wordsA = extractWords(a);
    const wordsB = extractWords(b);

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

    return common;
}

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

const common = 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
...