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

การเพิ่มฟังก์ชัน swapCase เข้า String Prototype - JavaScript

เพิ่มเมธอด swapCase() ให้ String.prototype เพื่อสลับตัวพิมพ์ใหญ่/เล็กของทุกตัวอักษร

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

const str = 'ThIS iS A CraZY StRInG';

String.prototype.swapCase = function() {
  let res = '';
  for (let i = 0; i < this.length; i++) {
    // ไม่ใช่ตัวอักษร (ตัวเลข, สัญลักษณ์, ช่องว่าง)
    if (this[i].toLowerCase() === this[i].toUpperCase()) {
      res += this[i];
      continue;
    }
    // ตัวพิมพ์เล็ก → พิมพ์ใหญ่
    if (this[i].toLowerCase() === this[i]) {
      res += this[i].toUpperCase();
      continue;
    }
    // ตัวพิมพ์ใหญ่ → พิมพ์เล็ก
    res += this[i].toLowerCase();
  }
  return res;
};

console.log(str.swapCase());

ผลลัพธ์

tHis Is a cRAzy sTriNg

ข้อควรระวัง

  • การแก้ไข prototype ของ built-in objects ถือเป็น anti-pattern ใน production
  • อาจก่อให้เกิด conflict กับ library อื่นหรือมาตรฐานอนาคต
  • ควรใช้ standalone function แทน

Standalone Version

const swapCase = str => [...str].map(c =>
  c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()
).join('');