ฟังก์ชันนี้ลบสระ (a, e, i, o, u) ตัวสุดท้ายของแต่ละคำในประโยค
ตัวอย่าง
// Input: 'This is an example string' // Output: 'Ths s n exampl strng'
ตัวอย่างโค้ด
const str = 'This is an example string';
const removeLast = word => {
const lastIndex = el => word.lastIndexOf(el);
// หาตำแหน่งสระสุดท้าย (max ของ lastIndex ของทุกสระ)
const ind = Math.max(
lastIndex('a'), lastIndex('e'), lastIndex('i'),
lastIndex('o'), lastIndex('u')
);
// ตัดตัวอักษรที่ตำแหน่ง ind ออก
return word.substr(0, ind) + word.substr(ind + 1);
};
const removeLastVowel = str => {
return str.split(' ')
.map(removeLast)
.join(' ');
};
console.log(removeLastVowel(str));
การทำงาน
- แยกคำด้วย
split(' ') - หาสระตัวสุดท้ายของแต่ละคำด้วย
lastIndexOf - ตัดตัวอักษรตำแหน่งนั้นออกด้วย
substr - รวมคำกลับด้วย
join(' ')
ผลลัพธ์
Ths s n exampl strng