ভূমিকা
একটি স্ট্রিং এবং একটি বাদ দেয়া শব্দের অ্যারে দেওয়া থাকলে, স্ট্রিং থেকে সেই শব্দগুলো মুছে ফেলা এবং এক্সট্রা হোয়াইটস্পেস সরিয়ে ক্লিন আউটপুট দেওয়া।
সম্পূর্ণ কোড
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"
কোড ব্যাখ্যা
- reduce() - প্রতিটি বাদ দেয়া শব্দের জন্য স্ট্রিং প্রসেস
- RegExp: `new RegExp(\` ${val}\`, "g")` - স্পেস + শব্দ, গ্লোবালি
- replace() - মিল পেলে খালি স্ট্রিং দিয়ে রিপ্লেস
- অর্ডার মেটার করে: বড় শব্দ আগে প্রসেস করা ভালো (partial match এড়াতে)
আউটপুট
The in is very similar to the in
⚠️ সমস্যাগুলো ও সমাধান
সমস্যা ১: শুধু " স্পেস + শব্দ" মэтচ করে
শুরুয়াতের শব্দ বা puntuations হ্যান্ডল করে না।
সমাধান: ওয়ার্ড বাউন্ডারি (\b) ব্যবহার
const removeWordsBetter = (str, words) => {
let result = str;
for (const word of words) {
// \b = ওয়ার্ড বাউন্ডারি, gi = গ্লোবাল + কেস-ইনসেনসিটিভ
const regex = new RegExp(`\\b${word}\\b`, 'gi');
result = result.replace(regex, '');
}
// একাধিক স্পেস ক্লিন আপ
return result.replace(/\s+/g, ' ').trim();
};
console.log(removeWordsBetter(string, words));
// "The in is very similar to the in"
সমস্যা ২: কেস-সেনসিটিভিটি
মূল কোড কেস-সেনসিটিভ। `'Weather'` মэтচ করবে না `'weather'`-এর সাথে।
সমাধান: 'i' ফ্ল্যাগ (উপরে দেখানো হয়েছে)
আধুনিক পদ্ধতি: একই রেজেক্সে সব শব্দ
const removeWordsOptimized = (str, words) => {
if (!words.length) return str;
// সব শব্দ জড়িয়ে একটি বড় রেজেক্স বানান
const escaped = words.map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
const regex = new RegExp(`\\b(?:${escaped.join('|')})\\b`, 'gi');
return str.replace(regex, '').replace(/\s+/g, ' ').trim();
};
ব্যবহারিক উদাহরণ
// ফিল্টারিং বাদ শব্দ (Stop words)
const stopWords = ['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at'];
const text = "The quick brown fox jumps over the lazy dog";
console.log(removeWordsOptimized(text, stopWords));
// "quick brown fox jumps over lazy dog"
// ইউজার ইনপুট স্যানিটাইজ
const bannedWords = ['spam', 'scam', 'fake'];
const userInput = "This is spam and scam content";
console.log(removeWordsOptimized(userInput, bannedWords));
// "This is and content"
সারাংশ
ওয়ার্ড বাউন্ডারি (`\b`) এবং কেস-ইনসেনসিটিভ (`i`) ফ্ল্যাগ ব্যবহার করুন। একাধিক রিপ্লেসের বদলে একটু রেজেক্স (`|` অপারেটর) দ্রুত এবং সঠিক। সবসময় স্পেস ক্লিন-আপ (`\s+`) করুন।