ভূমিকা
স্ট্রিং-এ কতগুলো স্পেস (whitespace) আছে তা গণনা করার অনেক পদ্ধতি আছে: split(), for লুপ, map/filter, বা রেগুলার এক্সপ্রেশন (regex)। বড় টেক্সটের জন্য regex-ভিত্তিক পদ্ধতিই সবচেয়ে দক্ষ এবং পারফরম্যান্স-বান্ধব।
Regex-ভিত্তিক সমাধান (প্রস্তাবিত)
console.log(("abc def rr tt".match(/ /g) || []).length); // 3
console.log(("a f fe fg gsd f".match(/ /g) || []).length); // 5
কোড ব্যাখ্যা
.match(/ /g)- স্ট্রিং-এ সব স্পেস খুঁজে বের করে (g = global flag)|| []- যদি স্পেস না থাকে তবেmatchnullরিটার্ন করে, তাই খালি অ্যারে ফলব্যাক হিসেবে ব্যবহার করা হয়েছে.length- মিল পাওয়া স্পেসগুলো গণনা করে
বিকল্প পদ্ধতিগুলো
১. split() মেথড
const str = "abc def rr tt";
const count = str.split(" ").length - 1; // 3
// নোট: একাধিক_SPACE থাকলে সঠিক ফলাফল দেবে না
২. for লুপ
function countSpaces(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === ' ') count++;
}
return count;
}
৩. filter() মেথড
const count = [...str].filter(char => char === ' ').length;
৪. reduce() মেথড
const count = [...str].reduce((acc, char) => acc + (char === ' ' ? 1 : 0), 0);
৫. সব whitespace (ট্যাব, নিউলাইন ইত্যাদি) গণনা
const count = (str.match(/\s/g) || []).length;
// \s = space, tab, newline, carriage return সব মিলে
পারফরম্যান্স তুলনা
বড় স্ট্রিং (১০০KB+) এর জন্য:
- Regex (match): সবচেয়ে দ্রুত, নেটিভ অপ্টিমাইজেশন
- for লুপ: খুব দ্রুত, মেমরি দক্ষ
- split/filter/reduce: ইন্টারমিডিয়েট অ্যারে তৈরি করে, মেমরি বেশি লাগে
এজ কেস হ্যান্ডলিং
function countSpacesRobust(str) {
if (typeof str !== 'string') return 0;
return (str.match(/ /g) || []).length;
}
console.log(countSpacesRobust("hello world")); // 1
console.log(countSpacesRobust("nospace")); // 0
console.log(countSpacesRobust("")); // 0
console.log(countSpacesRobust(null)); // 0
console.log(countSpacesRobust(123)); // 0
আউটপুট
3
5
সারাংশ
সাধারণ ব্যবহারের জন্য (str.match(/ /g) || []).length সেরা পদ্ধতি। সব whitespace ধরতে /\s/g ব্যবহার করুন।