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

การนับอักขระพิเศษในสตริงด้วย JavaScript

ภาพรวม

บทความนี้สาธิตวิธีนับจำนวนอักขระพิเศษ (Punctuation/Special Characters) ในสตริง โดยกำหนดชุดอักขระที่ต้องการนับล่วงหน้า

อักขระที่นับ

!, , , ', ;, ", ., -, ?

การนำไปใช้

const str = "This, is a-sentence;.Is this a sentence?";

const countSpecial = (str) => {
  const punct = "!,';.\"-?";
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (punct.includes(str[i])) {
      count++;
    }
  }
  return count;
};

console.log(countSpecial(str)); // 5

ผลลัพธ์

5

วิธีการทันสมัยกว่า

// ใช้ Regular Expression
const countSpecialRegex = (str) => {
  const matches = str.match(/[!,';.\"-?]/g);
  return matches ? matches.length : 0;
};

// ใช้ reduce
const countSpecialReduce = (str) => {
  const punct = new Set("!,';.\"-?");
  return [...str].reduce((count, char) => count + (punct.has(char) ? 1 : 0), 0);
};

การประยุกต์ใช้

  • การตรวจสอบความเข้มแข็งของรหัสผ่าน
  • การวิเคราะห์ข้อความ (Text Analysis)
  • การทำความสะอาดข้อมูล (Data Cleaning)

ข้อควรระวัง

หากต้องการนับอักขระพิเศษทั้งหมดตามมาตรฐาน Unicode ควรใช้ Unicode Property Escapes:

const countAllPunctuation = (str) => {
  const matches = str.match(/\p{P}/gu);
  return matches ? matches.length : 0;
};