How to get intersection of two strings in TypeScript

1 Answer

0 votes
function getIntersection(str1: string, str2: string): string {
  // Convert strings to sets to remove duplicates
  const set1: Set<string> = new Set(str1);
  const set2: Set<string> = new Set(str2);

  // Find the intersection
  const intersection: string[] = [...set1].filter(char => set2.has(char));

  // Return the result as a string
  return intersection.join('');
}

const string1 = "php";
const string2 = "python";

console.log(getIntersection(string1, string2));



/*
run:

"ph"

*/

 



answered Jul 7, 2025 by avibootz
...