ในภาษาอังกฤษ อักขระเหล่านี้ถือเป็นเครื่องหมายวรรคตอน -
'!', "," ,"\'" ,";" ,"\"", ".", "-" ,"?"
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและนับจำนวนการปรากฏของเครื่องหมายวรรคตอนเหล่านี้ในสตริงและส่งคืนการนับนั้น
ตัวอย่าง
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
const str = "This, is a-sentence;.Is this a sentence?";
const countPunctuation = str => {
const punct = "!,\;\.-?";
let count = 0;
for(let i = 0; i < str.length; i++){
if(!punct.includes(str[i])){
continue;
};
count++;
};
return count;
};
console.log(countPunctuation(str)); ผลลัพธ์
ผลลัพธ์ในคอนโซล:−
5