Viết hàm nhận 2 chuỗi, trả về chuỗi chứa tất cả ký tự chung (giữ nguyên thứ tự và số lần xuất hiện của chuỗi 1).
Ví dụ
Chuỗi 1: 'Hey There!!, how are you'
Chuỗi 2: 'Can this be a special string'
Ký tự chung: 'e here h are'
Giải pháp
Mã triển khai:
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])) {
res += str1[i];
}
}
return res;
};
console.log(commonString(str1, str2));
Kết quả
Đầu ra trong console:
e here h are
Lưu ý: Giữ trùng lặp từ str1 (nếu 'e' xuất hiện 3 lần trong str1 và có trong str2 → 3 'e' trong kết quả).