เราจำเป็นต้องเขียนฟังก์ชัน 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