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

สลับตัวพิมพ์เล็ก-ใหญ่ในสตริง (Flip Case) - JavaScript

แปลงตัวพิมพ์ใหญ่เป็นเล็ก และตัวพิมพ์เล็กเป็นใหญ่ ในสตริง โดยใช้ ASCII Code

ตัวอย่าง

'The Case OF tHis StrinG Will Be FLiPped'
→ 'tHE cASE of ThIS sTRINg wILL bE flIpPED'

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

const str = 'The Case OF tHis StrinG Will Be FLiPped';

const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0) <= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;

const flipCase = str => {
  let newStr = '';
  const margin = 32; // ASCII difference between upper/lower
  
  for (let i = 0; i < str.length; i++) {
    const curr = str[i];
    if (isLowerCase(curr)) {
      newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
    } else if (isUpperCase(curr)) {
      newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
    } else {
      newStr += curr;
    }
  }
  return newStr;
};

console.log(flipCase(str));

ผลลัพธ์

tHE cASE of ThIS sTRINg wILL bE flIpPED

วิธีแบบ Built-in (แนะนำ)

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

ใช้ toUpperCase() / toLowerCase() จัดการ Unicode ได้ถูกต้องกว่า ASCII