เราได้รับสตริงและอาร์เรย์สตริง หน้าที่เขียนฟังก์ชันลบ substring ทั้งหมดที่อยู่ในอาร์เรย์ออกจากสตริง
substring เหล่านี้เป็นคำสมบูรณ์ เราต้องลบ whitespace นำหน้าหรือท้ายด้วย เพื่อไม่ให้มี whitespace ติดกันสองช่อง
เขียนโค้ด
ตัวอย่าง
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));
ผลลัพธ์
ผลลัพธ์ของโค้ดนี้จะเป็น
The in is very similar to the in