Cho chuỗi và mảng từ, xóa tất cả từ trong mảng khỏi chuỗi, loại bỏ khoảng trắng thừa.
Dùng reduce() với RegExp global thay thế từng từ.
Ví dụ
const string = "The weather in Delhi today is very similar to the weather in Mumbai"; const words = [ 'shimla','rain','weather','Mumbai','Pune','Delhi','tomorrow','today','yesterday' ]; const removeWords = (str, arr) => { return arr.reduce((acc, val) => { const regex = new RegExp(` ${val}`, "g"); return acc.replace(regex, ''); }, str); }; console.log(removeWords(string, words));Kết quả
Đầu ra:
The in is very similar to the in