นับจำนวนเครื่องหมายวรรคตอน (punctuation) ในสตริงภาษาอังกฤษ
เครื่องหมายที่นับ
! , ' ; " . - ?
ตัวอย่างโค้ด
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])) count++;
}
return count;
};
console.log(countPunctuation(str));
ผลลัพธ์
5
วิธีแบบ Regex (ทันสมัย)
const countPunctuation = str => (str.match(/[!,'";.\-?]/g) || []).length;
ใช้ Character Class [...] ใน Regex จับคู่ได้ทุกตัวที่ระบุ