ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงตัวอักษรพิมพ์เล็ก และตัวเลข num ฟังก์ชันควรลบตัวอักษร num ตัวจากสตริงตามลำดับอักษร หมายถึง ลบ 'a' ก่อนถ้ามี แล้ว 'b', 'c' ... จนครบ num ตัว
ตัวอย่าง
โค้ดตัวอย่างด้านล่าง:
const str = 'abascus';
const num = 4;
const removeAlphabetically = (str = '', num = '') => {
const legend = "abcdefghijklmnopqrstuvwxyz";
for (let i = 0; i < legend.length; i += 1) {
while (str.includes(legend[i]) && num > 0) {
str = str.replace(legend[i], "");
num -= 1;
}
}
return str;
};
console.log(removeAlphabetically(str, num));
ผลลัพธ์
sus
คำอธิบายเพิ่มเติม
จาก 'abascus' ลบ 4 ตัว: ลบ a (2 ตัว) เหลือ bscus ลบ b (1 ตัว) เหลือ scus ลบ c (1 ตัว) เหลือ sus รวม 4 ตัว โค้ดใช้ replace() ที่แทนที่แค่ครั้งแรก จึงต้อง while loop