Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

두 문자열 사이의 공유 요소 찾기 - JavaScript

<시간/>

우리는 몇 가지 공통 요소를 포함하거나 포함하지 않을 수 있는 두 개의 문자열을 취하는 JavaScript 함수를 작성해야 합니다. 함수는 공통 요소가 없으면 빈 문자열을 반환해야 합니다. 그렇지 않으면 두 문자열 사이의 모든 공통 요소를 포함하는 문자열입니다.

다음은 두 개의 문자열입니다 -

const str1 = 'Hey There!!, how are you';
const str2 = 'Can this be a special string';

예시

다음은 코드입니다 -

const str1 = 'Hey There!!, how are you';
const str2 = 'Can this be a special string';
const commonString = (str1, str2) => {
   let res = '';
   for(let i = 0; i < str1.length; i++){
      if(!str2.includes(str1[i])){
         continue;
      };
      res += str1[i];
   };
   return res;
};
console.log(commonString(str1, str2));

출력

다음은 콘솔의 출력입니다 -

e here h are