Chúng ta cần viết hàm JavaScript nhận vào hai chuỗi làm đối số. Hàm kiểm tra hai chuỗi để tìm các ký tự chung và tạo thành chuỗi mới từ các ký tự đó, sau đó trả về chuỗi đó.
Ví dụ
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));Kết quả
Kết quả in ra console:
[ 'l', 'lo', 'lov', 'love', 'o', 'ov', 'ove', 'v', 've', 'e' ]