เราได้รับสตริงและอาร์เรย์ของสตริง งานของเราคือการเขียนฟังก์ชันที่ลบสตริงย่อยทั้งหมดที่มีอยู่ในอาร์เรย์ออกจากสตริง
สตริงย่อยเหล่านี้เป็นคำที่สมบูรณ์ เราจึงควรลบช่องว่างนำหน้าหรือต่อท้ายเพื่อไม่ให้ช่องว่างสองช่องปรากฏขึ้นพร้อมกัน
ดังนั้น เรามาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
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