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

แปลงตัวอักษร index คี่/คู่ เป็นพิมพ์ใหญ่/เล็กในสตริง JavaScript

เราต้องเขียนฟังก์ชันอ่านสตริงและแปลงตัวอักษร index คี่เป็นพิมพ์ใหญ่ และ index คู่เป็นพิมพ์เล็ก แล้วคืนสตริงใหม่

โค้ดเต็ม

ตัวอย่าง

const text = 'Hello world, it is so nice to be alive.';
const changeCase = (str) => {
  const newStr = str
    .split("")
    .map((word, index) => {
      if(index % 2 === 0){
        return word.toLowerCase();
      }else{
        return word.toUpperCase();
      }
    })
    .join("");
  return newStr;
};
console.log(changeCase(text));

โค้ดแปลงสตริงเป็นอาร์เรย์ map ผ่านแต่ละคำ แปลงเป็นพิมพ์ใหญ่/เล็กตาม index แล้วรวมกลับเป็นสตริง

ผลลัพธ์

hElLo wOrLd, It iS So nIcE To bE AlIvE.