Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การนับจำนวนสระในสตริงด้วย JavaScript

บทความนี้สาธิตฟังก์ชันนับจำนวนสระ (a, e, i, o, u) ในสตริงที่กำหนด

ตัวอย่างโค้ด

const str = 'this is a string';

const countVowels = (str = '') => {
  str = str.toLowerCase();
  const legend = 'aeiou';
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    const el = str[i];
    if (!legend.includes(el)) {
      continue;
    }
    count++;
  }
  return count;
};

console.log(countVowels(str));

ผลลัพธ์

4

คำอธิบาย

แปลงสตริงเป็น lowercase ก่อน แล้ววนลูปตรวจสอบแต่ละตัวอักษรว่าอยู่ใน 'aeiou' หรือไม่ นับจำนวนที่พบ

วิธีทางเลือก: ใช้ regex (str.match(/[aeiou]/gi) || []).length