เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสองสตริงเป็นอาร์กิวเมนต์ จากนั้นฟังก์ชันควรตรวจสอบสองสตริงเพื่อหาอักขระทั่วไปและเตรียมสตริงใหม่ของอักขระเหล่านั้น
สุดท้าย ฟังก์ชันควรส่งคืนสตริงนั้น
รหัสสำหรับสิ่งนี้จะเป็น −
ตัวอย่าง
const str1 = "IloveLinux";
const str2 = "weloveNodejs";
const findCommon = (str1 = '', str2 = '') => {
const common = Object.create(null);
let i, j, part;
for (i = 0; i < str1.length - 1; i++) {
for (j = i + 1; j <= str1.length; j++) {
part = str1.slice(i, j);
if (str2.indexOf(part) !== −1) {
common[part] = true;
}
}
}
const commonEl = Object.keys(common);
return commonEl;
};
console.log(findCommon(str1, str2)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[ 'l', 'lo', 'lov', 'love', 'o', 'ov', 'ove', 'v', 've', 'e' ]