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

เปลี่ยนเคสสตริงตามเงื่อนไขตัวแรก - JavaScript

เปลี่ยนสตริงทั้งหมดเป็นตัวพิมพ์ใหญ่ ถ้าตัวแรกเป็นพิมพ์ใหญ่ มิฉะนั้นเป็นตัวพิมพ์เล็กทั้งหมด

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

const str1 = 'This is a normal string';
const str2 = 'thisIsACamelCasedString';

const changeStringCase = str => {
  const isUpper = str[0].charCodeAt(0) >= 65 && str[0].charCodeAt(0) <= 90;
  return isUpper ? str.toUpperCase() : str.toLowerCase();
};

console.log(changeStringCase(str1)); // THIS IS A NORMAL STRING
console.log(changeStringCase(str2)); // thisisacamelcasedstring

ผลลัพธ์

THIS IS A NORMAL STRING
thisisacamelcasedstring

วิธีแบบ Built-in (ง่ายกว่า)

const changeStringCase = str => 
  str[0] === str[0].toUpperCase() 
    ? str.toUpperCase() 
    : str.toLowerCase();

ใช้ toUpperCase() เปรียบเทียบตัวแรก จัดการ Unicode ได้ดีกว่า ASCII range