ภาพรวม
เราต้องเขียนฟังก์ชัน 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'
]